简体   繁体   中英

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 like 1.344E-12.

Is there a built in way to round a scientific notation value to x number of decimals?

Use a format string like

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

Here "E" means to use scientific notation (with capital "E", use "e" if you want a small one...) and 3 stands for three digits after the decimal point.

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

EDIT

If you want more flexibility, you can use Custom numeric Format Strings . Using these you can eg also specify the number of digits used for the exponent like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM