Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

c# - ToString("D3") is not working

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...