Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with C# double format

I am using next code to format double value:

String.Format("${0:0,0.#}",...);

It working great, but when numbers are less than 10, I got problem. Numbers are displayed as $03, $06 for example.

Please advise me correct string to have a double number in next format ddd,ddd,ddd,ddd.dd

like image 383
Anton Avatar asked Apr 11 '26 02:04

Anton


1 Answers

Try this instead:

string result = string.Format("${0:#,##0.00}", d);

If your double represents a currency you should use:

string result = string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:c}", d);

Note that if you omit the CultureInfo.InvariantCulture it could display using something other than $ on some computers. For example on my computer string.Format("{0:c}", d) gives 2,00 kr which might not be what you wanted.

In your example you don't actually need to use string.Format at all. You could use this instead:

string s = d.ToString("c", CultureInfo.GetCultureInfo("en-US"));

As well as being clearer and more concise, it also has the advantage of avoiding boxing. Of course if your format string is more complex than in your example then it would make sense to use string.Format.

And as a final remark I'd recommend against using doubles to store currency. A decimal type is probably more appropriate.

like image 169
Mark Byers Avatar answered Apr 12 '26 14:04

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!