Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert string to decimal separator "." and "," insensitive way?

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!

like image 512
Andrew Florko Avatar asked Nov 04 '10 05:11

Andrew Florko


People also ask

How do you convert strings to decimals?

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.

What is the correct decimal separator?

Both a comma and a period (or full-stop) are generally accepted decimal separators for international use.

How do you convert an empty string to a decimal?

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.

How do I change decimal separator in IOS?

Select System Preferences. Select Language and Region. Click Advanced. Change the Decimal separator from a comma (,) to a full stop (.)


Video Answer


3 Answers

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
like image 129
Jeff Mercado Avatar answered Oct 16 '22 08:10

Jeff Mercado


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); 
like image 12
Friend Avatar answered Oct 16 '22 07:10

Friend


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);
like image 7
Noon Silk Avatar answered Oct 16 '22 07:10

Noon Silk