Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to decimal conversion: dot separation instead of comma

Tags:

c#

decimal

I have a string read from a textbox. It contains a comma for decimal separation.

I have NumberFormatInfo.CurrencyDecimalSeparator set to , (comma) but when I convert the string to decimal Convert.ToDecimal(mystring); I obtain a dot separate value for decimal.

Example:

decimal a=Convert.ToDecimal("1,2345"); ----> decimal is 1.2345 

I have tried also:

double a=Convert.ToDouble("1,2345");  

but dot for decimal again

like image 947
LoveMyWife Avatar asked Nov 10 '13 18:11

LoveMyWife


People also ask

How do you change string to decimal?

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.

Why is there a comma instead of decimal?

as a separator between the dollars and cents. Some countries use a comma (,) instead of a decimal to indicate that separation. In addition, while the U.S. and a number of other countries use a comma to separate thousands, some countries use a decimal point for this purpose.

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. TryParse() - I think that was available in 1.1.

Which countries use decimal instead of comma?

The decimal point is generally used in countries such as China, Japan, Malaysia, Singapore, Sri Lanka, The Philippines, etc. Some others use the decimal comma, as is the case in Indonesia and Mongolia.


1 Answers

All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:

var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US")); // (or 1,2345 with your local culture, for instance) 

(obviously, you should replace the "en-US" with the culture of your number local culture)

the same way, if you want to do ToString()

d.ToString(new CultureInfo("en-US")); 
like image 153
Agat Avatar answered Sep 25 '22 08:09

Agat