Decimal.TryParse doesn't parse my decimal value - c#

When I tried to convert something like 0.1 (from user in textbox), My value b is always false.
bool b = Decimal.TryParse("0.1", out value);
How can it be here to work?

Specify the culture for the parsing. Your current culture uses some different number format, probably 0,1.
This will successfully parse the string:
bool b = Decimal.TryParse("0.1", NumberStyles.Any, CultureInfo.InvariantCulture, out value);

Too late to the party, but I was going to suggest forcing the culuture to en-US but Invariant is a better sln
decimal value;
bool b = Decimal.TryParse("0.1", NumberStyles.Any, new CultureInfo("en-US"), out value);

Use Culture in overload method

Related

Globalization .net convert string to double

İ have string like this and i want to convert it to double.
string x = "65.50";
double y = Convert.ToDouble(x);
But the result is 6550.0
i want it to be 65.50.
I am using ASP.NET and C#. I think it is a problem about globalization.
This is my for question sorry about that (:
Yes, it's your current culture that converts it this way. You can use CultureInfo.InvariantCulture to skip using your culture.
double d = double.Parse("65.50", CultureInfo.InvariantCulture);
i want it to be 65.50.
If you want to convert it back to string:
string str = d.ToString("N2", CultureInfo.InvariantCulture);
I assume this is a currency since you keep the decimal places. Then you should use decimal instead:
decimal dec = decimal.Parse("65.50", CultureInfo.InvariantCulture); // 65.5
Now you can use decimal.ToString and it automagically restores the decimal places:
string str = dec.ToString(CultureInfo.InvariantCulture); // "65.50"
Recently i had a similar problem. The solution :
var result = Double.TryParse(x, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out y);
if you get true, that's x is converted to double
Try this:
var res = Double.Parse("65.50", NumberStyles.Float, CultureInfo.InvariantCulture);
It will parse it with culture where . is floating separator
Here you can try it: http://ideone.com/3LMVqa

Convert String to Double with Known Format

I need to convert a string back to a double, but the string is not always the same format. In one case it is "N0", in another "#,##", and yet another is currency "C0". The good thing is, I know what format the string is in as earlier in the process it was converted from double to string.
How can I convert back to a double. The numeric only values double.parse or Convert.ToDouble with ease, but the currency values do not.
string format = "{0:C0}";
double dollar = 1,234.00;
string dollarString = String.Format(format, doubleValue); // == "$1,234"
double newDollar = Convert.ToDouble(dollarString); // Fails
This last line is where the issue is. I'm assuming I need to use IFormatProvider or Culture or something, but I'm not exactly sure.
I cannot specifically reference the format is a Currency as the "format" isn't always a currency.
Ideas?
As I was typing this I came up with the following. Further feedback on whether this is a good way of doing it or if I might run into issues later.
double newDollar;
double.TryParse(dollarString, NumberStyles.Any, CultureInfo.CurrentCulture.NumberFormat, out newDollar);
If you're using CultureInfo.CurrentCulture make sure to you set the CurrentCulture of your thread.
Else it can end up in parsing it the wrong way (depending on the language settings on your computer).
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Then you can safely use this:
double.TryParse(dollarString, NumberStyles.Any,
CultureInfo.CurrentCulture.NumberFormat, out newDollar);
Alternatively, you can create a function like this (To get the right format without setting the culture).
side note: In Switzerland, this could cause troubles because the euros can still be parsed.
So 5,05 (€) would successfully be parsed to 505 (CHF). Trust me, you don't want this to happen.
public static double GetDouble(string value, double defaultValue)
{
double numberToConvert;
if (!double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.CurrentCulture, out numberToConvert) &&
!double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.GetCultureInfo("en-US"), out numberToConvert) &&
!double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture, out numberToConvert))
{
numberToConvert= defaultValue;
}
return numberToConvert;
}

decimal.TryParse returns false

The input string in textbox is, say, $10.00 . I call
decimal result;
var a = decimal.TryParse(text, NumberStyles.AllowCurrencySymbol, cultureInfo, out result);
cultureInfo is known (en-US). Why does decimal.tryParse returns false?
Thank you.
The problem is you've allowed the currency symbol itself, but you've omitted other properties that are required to parse it correctly (decimal point, for example.) What you really want is NumberStyles.Currency:
decimal.TryParse("$10.00", NumberStyles.Currency, cultureInfo, out result);
Try this, you need to include NumberStyles.Number in the bitwise combination of values for the style argument:
decimal result;
var a = decimal.TryParse(text, NumberStyles.Number | NumberStyles.AllowCurrencySymbol, cultureInfo, out result);
You forgot to allow the decimal point, too:
decimal result;
var enUS = new System.Globalization.CultureInfo("en-US");
var a = decimal.TryParse("$10.00", System.Globalization.NumberStyles.AllowCurrencySymbol | System.Globalization.NumberStyles.AllowDecimalPoint , enUS, out result);
Console.WriteLine(enUS);
Console.WriteLine(a);
Console.WriteLine(result);

How do I convert a string to a decimal, and format it for pretty output?

I want to convert "372551.40" to decimal. But I need to see it after converting this format 372.551,40.
To convert it to decimal, you can use:
decimal decimalValue = 0.0;
decimalValue = decimal.Parse("372551.40");
or
decimal.TryParse("372551.40", out decimalValue);
To display it in a specific format you can do:
CultureInfo tr = new CultureInfo("tr-TR");
string formattedValue = decimalValue.ToString("c", tr);
//result will be 372.551,40 YTL
formattedValue = decimalValue.ToString("0,0.00", tr);
//result will be 372.551,40
string value;
Decimal number;
value = "16,523,421";
if (!Decimal.TryParse(value,out number))
{
// set it to something if the "Value" is not a number
number = -1;
}
Do the following:
string s = "372551.40";
CultureInfo cultureInfo = CultureInfo.InvariantCulure; //Use relevant culture in which your number is formatted. In this case InvariantCulture would do.
decimal d;
bool succesful = Decimal.TryParse(s, NumberStyles.Number, cultureInfo, out d); //it will try to parse the string according to the specified culture.;
If you have a succesful parse, then d will store the numeric value represented by s as a decimal value which you can output into any formatted string and culture the ToString() or Format.String().
Note that if the culture in which the number represented by s is the current system culture, then you can use the TryParse(string s, out decimal d) overload where it is not necessary to specify NumberStyles and IFormatProvider.
Something like this?
string s = "372551.40";
decimal d;
if (decimal.TryParse(s, out d))
{
var culture = new CultureInfo("de-DE");
var result = d.ToString("0,0.00", culture);
// result is "372.551,40"
}
You can also use the current culture instead of hard-coding one like I did.
Hope this helps,
John
Use decimal.Parse() to make it a decimal. Then you have many formatting options.
The display as you mentioned is dependent on the culture setting.
Make your new CultureInfo and in the NumberFormat, you will have to modify some settings like Decimal Separator as , and Thousands Separator as . and provide this to the ToString method of the variable holding the decimal value.
This should display the value as 372.551,40
You can use .Replace
string string 1 = "372,551.40";
string1.Replace(",","");
decimalVal = System.Convert.ToDecimal(StringVal);
//shows 372551.40
You can always throw that into a for loop if you are playign with a ton of numbers.
You can find more in depth info and some examples on MSDN
The overload of decimal.Parse that takes an IFormatProvider will allow you to parse strings containing numbers with periods as decimal point symbols (in case the standard is a comma in your culture).
You can use ToString on the resulting decimal to format it with a comma by passing in an appropriate IFormatProvider. Both CulturInfo and NumberFormatInfo implement IFormatProvider.
You can get an instance of CultureInfo with the following code (this one is for English in Australia).
new CultureInfo("en-AU")
Also note that decimal.TryParse is a good alternative to the decimal.Parse method if you expect incorrectly formatted strings as it will allow you to handle them without an exception being raised.
The following code should give you the desired result (you wrote in one of the comments that the target system is SAP and that the culture is probably German (de-DE)).
var yourString = "372551.40";
var yourDecimal = decimal.Parse(yourString, CultureInfo.InvariantCulture);
var yourFormattedDecimal = yourDecimal.ToString(new CultureInfo("de-DE"));
From MSDN:
string value;
decimal number;
// Parse an integer with thousands separators.
value = "16,523,421";
number = Decimal.Parse(value);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// 16,523,421' converted to 16523421.
Cheers
You can create custom NumberFormatInfo:
string s = "372551.40";
var dec = decimal.Parse(s, CultureInfo.InvariantCulture);
var nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.NumberGroupSeparator = ".";
nfi.NumberDecimalSeparator = ",";
var res = dec.ToString("n", nfi);
var resDecimal = decimal.Parse(res, nfi);
Output is exactly what you need: 372.551,40

String.Format consider locale or not?

Is it true that String.Format works 2 ways:
if we use built-in format such as C, N, P.... it will take locale settings into account?
if we use custom format code such as #,##0.000 it will NOT take locale settings into account?
In my code, I use method like this
String.Format("{0:#.##0,000}", value);
because my country use comma as decimal separator
but the result still is: 1,234.500 as if it consider dot as decimal separator.
Please help!
You want to use CultureInfo:
value.ToString("N", new CultureInfo("vn-VN"));
Using String.Format:
String.Format(new CultureInfo("vi-VN"), "N", value);
Since you're in Hanoi (from profile), I used Vietnam's code, which is vn-VN.
This works. The formatted value is 123.456,789 which is correct per es-ES
IFormatProvider iFormatProvider = new System.Globalization.CultureInfo("es-ES");
var value = 123456.789001m;
string s = value.ToString("#,##0.000", iFormatProvider);
string s2 = string.Format(iFormatProvider, "{0:#,##0.000}", value);
FormattableString fs = $"{value:#,##0.000}";
string s3 = fs.ToString(iFormatProvider);
Note that the , and . are using a 'standard' en-US style, but .ToString() and string.Format() with a format provider does the right thing.
You should make sure your thread uses the correct culture:
Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture
Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture
FrameworkElement.LanguageProperty.OverrideMetadata(GetType(FrameworkElement), New FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)))

Categories

Resources