How to specify total number of character in C# number formatting?
Is there a way to specify total number of characters when formatting doubles?
Lets say I have 0.00012345678开发者_JS百科, and I specify total number of characters (7), I want to get 1.23e-4. Format "G7" would give 1.2345e-4.
More examples:
0.00000012345678F -> 1.23e-7
0.00012345678F -> 1.23e-4
0.12345678F -> 1.23e-1
1.2345678F -> 1.23457
12.345678F -> 12.3457
12345678F -> 1.234e8
You probably want to use the "e" format string like so...
String.Format("{0:0.00e+0}", number);
You have a misunderstanding about the meaning of "precision". For a floating point number, "precision" means the number of significant digits, so the result returned by "G6" is correct.
If you want a fixed number of characters, use a custom format string like Jason suggested.
{0:00e+0}
http://blog.stevex.net/string-formatting-in-csharp/
精彩评论