Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing Numbers in Exponential form

Tags:

c#

I have a requirement to convert the following types of decimal numbers to exponential format

Number 0.00001formatted as 0.01E-04

I use the following method for this: string.Format("{0:E2}", dValue);

But this returns 0.01E-004

So I need to restrict the number of digits to 2 after the E. Is this possible? If so: how ?

like image 703
siva Avatar asked Feb 14 '12 07:02

siva


2 Answers

You'll need to use a custom format string to specify how to format your decimal:

string.Format("{0:0.##E+00}", dValue);

You can find more about custom numeric format strings on the MSDN here. There's a specific section on Exponent formats.

like image 137
Paul Turner Avatar answered Nov 15 '22 13:11

Paul Turner


I think you want something like:

string text = dValue.ToString("0.###E+00");

(Change the number of # characters to change the number of decimal digits before the E.)

You can do this with a compound format specifier as well by calling string.Format, but personally I'd use a simple one unless you need to put other text round it anyway, in which case you'd use use something like:

string text = string.Format("Before {0:0.0###E+00} After", dValue);
like image 22
Jon Skeet Avatar answered Nov 15 '22 13:11

Jon Skeet