Application deals with strings that represent decimals that come from different cultures. For example "1.1 and "1,1" is the same value.
I played with Decimal.TryParse
flags combinations but couldn't achieve the result I want. "1,1" became "11" or "0" after all.
Is it possible to convert such strings to decimal in one line of code without pre-replacing "," char to "." or playing with NumberFormat.NumberDecimalSeparator
?
How do you handle such situations?
Thank you in advance!
Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.
Both a comma and a period (or full-stop) are generally accepted decimal separators for international use.
It's not possible to convert an empty string to a number (decimal or not). You can test for an empty string before trying the conversion or use decimal.
Select System Preferences. Select Language and Region. Click Advanced. Change the Decimal separator from a comma (,) to a full stop (.)
You can create a temporary CultureInfo
object to use when you parse.
// get a temporary culture (clone) to modify
var ci = CultureInfo.InvariantCulture.Clone() as CultureInfo;
ci.NumberFormat.NumberDecimalSeparator = ",";
decimal number = decimal.Parse("1,1", ci); // 1.1
I found another way to do it. It looks odd but it works fine for me.
So if you don't know culture of the target system and you don't know which value you will get like 12.33 or 12,33 you can do following
string amount = "12.33";
// or i.e. string amount = "12,33";
var c = System.Threading.Thread.CurrentThread.CurrentCulture;
var s = c.NumberFormat.CurrencyDecimalSeparator;
amount = amount.Replace(",", s);
amount = amount.Replace(".", s);
decimal transactionAmount = Convert.ToDecimal(amount);
You just need to have the correct culture set, when calling Parse
, like so:
string s = "11,20";
decimal c1 = decimal.Parse(s, new CultureInfo("fr-FR"));
decimal c2 = decimal.Parse(s, new CultureInfo("en-AU"));
Console.WriteLine(c1);
Console.WriteLine(c2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With