views:

93

answers:

4

Is there a way to specify total number of characters when formatting doubles?

Lets say I have 0.00012345678, 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
A: 

See this link: http://msdn.microsoft.com/en-us/library/kfsatb94.aspx

Roatin Marth
+2  A: 

You probably want to use the "e" format string like so...

String.Format("{0:0.00e+0}", number);
Jason Punyon
Thanks, it works with my example, but that's not exactly what I want :) Let me try to give more details: my goal is to be able to specify total number of characters in the output, so if I specify 4 I want to get these results:0.00000012345678F -> 1.23e-70.00012345678F -> 1.23e-40.12345678F -> 1.23e-11.2345678F -> 1.234512.345678F -> 12.345
Paulius
+1  A: 

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.

Heinzi