C # Round Scientific Notation Value

I have a small double value that is formatted in scientific notation. When I display the value, it is displayed in the format 1.34423E-12 with 5 digits after the decimal. I would like to round this value so that it displays as 1.344E-12.

Is there a built-in way to round a scientific notation value to x number of decimal places?

+3


source to share


1 answer


Use a format string like

double d = 1.34423e-12;
string formattedValue = d.ToString("E3");

      

Here it "E"

means using scientific notation (with capital "E", use "E"

if you want small ...), 3

meaning three digits after the decimal point.

You can look at Standard Numeric Format Strings on MSDN to see other options. The documentation for the String.Format method also contains useful information about formatting values.



EDIT

If you need more flexibility, you can use Custom Numeric Formatted Strings . Using these you can, for example, also specify the number of digits used for the indicator, for example

d.ToString("0.000E0"); // -> Results in "13.344E-12" instead of "13.344E-012"
d.ToString("0.000E0000"); // -> "13.344E-0012"

      

+3


source







All Articles