Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToString("D3") is not working

Tags:

c#

double Cost = 0.03;    
var ttt = Cost.ToString("D3");

and

System.FormatException: Format specifier was invalid.

Why?

http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#DFormatString

Says it's ok?

like image 644
Pinch Avatar asked Apr 01 '14 18:04

Pinch


2 Answers

Take another look at your MSDN link, just a few sections higher up in the same document:

"D" or "d"

Decimal

Result: Integer digits with optional negative sign.
Supported by: Integral types only.
Precision specifier: Minimum number of digits.
Default precision specifier: Minimum number of digits required.
More information: The Decimal("D") Format Specifier.

1234 ("D") -> 1234
-1234 ("D6") -> -001234

(Emphasis mine)

If you want to ensure three digits to the left of decimal point (this is what 'D' does) with a floating-point type value, you will need to use a Custom Numeric Format String.

Cost.ToString("000.########");

But based on your comments, you really want it to the right of the decimal point, in which case the 'F' strings will work:

Cost.ToString("F3");

And if you're worried about the leading zero, you can do this:

Cost.ToString(".000");
like image 149
Joel Coehoorn Avatar answered Sep 18 '22 00:09

Joel Coehoorn


based on your comment (4.4546 should be displayed as a string "4.455"), this should work:

var cost = 4.4546d;
var ttt = cost.ToString("0.000");
like image 42
vlad Avatar answered Sep 18 '22 00:09

vlad