10

c# decimal.toString() conversion problem

Example: I have a value in decimal(.1) when I convert decimal to string using toString() it returns (0,10). Instead of .(DOT) it returns ,(COMMA).

Steve Lillis
  • 3,148
  • 5
  • 18
  • 41
sivaprakash
  • 147
  • 1
  • 11
  • Check the current Locale settings - you will need to select one which use . rather than , - The opposite to this question really : http://stackoverflow.com/questions/1559185/formatting-numbers-as-strings-with-commas-in-place-of-decimals – PaulF Jun 17 '15 at 10:41
  • Output depends on you `CurrentCulture`, ToString(CultureInfo) – Mikko Viitala Jun 17 '15 at 10:41
  • possible duplicate of [Set up dot instead of comma in numeric values](http://stackoverflow.com/questions/9160059/set-up-dot-instead-of-comma-in-numeric-values) – Risadinha Jun 17 '15 at 11:19

5 Answers5

10

I believe this is to do with the culture/region which your operating system is set to. You can fix/change the way the string is parsed by adding in a format overload in the .ToString() method.

For example

decimalValue.ToString(CultureInfo.InvariantCulture);
Ralt
  • 1,874
  • 1
  • 22
  • 35
4

you have to define the format, it will depend in your local setting or define the format, using something like this

decimal.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));

cheers

brothers28
  • 1,186
  • 15
  • 21
AASanchezA
  • 41
  • 2
3

For this to be happening, the thread's current culture must be one that uses a separator of comma instead of dot.

You can change this on a per ToString basis using the overload for ToString that takes a culture:

var withDot = myVal.ToString(CultureInfo.InvariantCulture);

Alternatively, you can change this for the whole thread by setting the thread's culture before performing any calls to ToString():

var ci = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;

var first = myVal.ToString();
var second = anotherVal.ToString();
Steve Lillis
  • 3,148
  • 5
  • 18
  • 41
1

For comma (,)

try this:

decimalValue.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("tr-tr"))
emert117
  • 888
  • 2
  • 11
  • 23
0

Then your current culture's NumberDecimalSeparator is , instead of ..

If that's not desired you can force the dot with CultureInfo.InvariantCulture:

decimal num = 0.1m;
string numWithDotAsSeparator = num.ToString(CultureInfo.InvariantCulture);

or NumberFormatInfo.InvariantInfo

string numWithDotAsSeparator = num.ToString(NumberFormatInfo.InvariantInfo)
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859