Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

I need to convert a decimal to a string with N decimals (two or four) and NO thousand separator:

'XXXXXXX (dot) DDDDD'

The problem with CultureInfo.InvariantCulture is that is places ',' to separate thousands.

UPDATE

This should work for decimal and double types.


My previous question: Need to convert double or decimal to string

like image 400
Captain Comic Avatar asked Nov 02 '10 10:11

Captain Comic


People also ask

How do you convert a string to two decimal places?

Round(temp, 2); Alternatively, if you want the result as a string, just parse it and format it to two decimal places: double temp = Double.

What is the correct decimal separator?

This symbol can be a period ("."), as is common in United States and other English-speaking countries, or a comma (","), as in continental Europe. Decimal point and decimal comma are also common names for the decimal separator.

What is the thousand separator format?

The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.

What is used as a separator for decimal numbers in Calc?

as decimal sign instead of a comma? Some languages, like French, Italian, German, or Portuguese, use a comma as decimal separator. The appearance of numbers in Calc depends on the language settings.


2 Answers

For a decimal, use the ToString method, and specify the Invariant culture to get a period as decimal separator:

value.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) 

The long type is an integer, so there is no fraction part. You can just format it into a string and add some zeros afterwards:

value.ToString() + ".00" 
like image 94
Guffa Avatar answered Sep 29 '22 15:09

Guffa


It's really easy to specify your own decimal separator. Just took me about 2 hours to figure it out :D. You see that you were using the current ou other culture that you specify right? Well, the only thing the parser needs is an IFormatProvider. If you give it the CultureInfo.CurrentCulture.NumberFormat as a formatter, it will format the double according to your current culture's NumberDecimalSeparator. What I did was just to create a new instance of the NumberFormatInfo class and set it's NumberDecimalSeparator property to whichever separator string I wanted. Complete code below:

double value = 2.3d; NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "-"; string x = value.ToString(nfi); 

The result? "2-3"

like image 36
Pedro Santos Avatar answered Sep 29 '22 15:09

Pedro Santos