仅当需要科学记数法 [英] Use scientific notation only if needed
问题描述
我要将 double
值解析为字符串
。我想让我的号码有一个指定的位数(我不会知道,直到运行时)。如果这个数字可以用非零值表示数字位数,这是我想要的。
I want to parse a double
value into a string
. I want my number to have a specified number of digits (that I won't know until runtime). If this number can be expressed with a non-zero value in number of digits this is what I want. If the number comes out as zero's like this I want it expressed in scientific notation.
一些例子会使这个更清楚,这里假设我想要3个数字:
Some examples will make this more clear, this assumes I wanted 3 digits:
价值: .2367 输出:0.23
Value: .2367 Output: "0.23"
价值: .00367 输出:3.67E-3
Value: .00367 Output: "3.67E-3"
价值: 22.3 输出:22.3
Value: 22.3 Output: "22.3"
值: 3364.0 输出:
我的解决方案将使用 ToString()方法和 N
数字格式字符串,如果它导致零的还原为 E
格式字符串,但这感觉像重新发明轮子。
My work around solution would use the ToString() method and the N
numeric format string and if it results in zero's revert to the E
format string, but this feels like reinventing the wheel. Does anyone know if a built in method to do this?
推荐答案
有没有看过使用常规数字格式说明符?
一般(G)格式说明符将数字转换为定点或科学记数法最多的
压缩,取决于数字的
类型以及是否存在精度说明符。
The general ("G") format specifier converts a number to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present.
文档中的一些示例: / p>
Some samples from the documentation:
double number;
number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023
number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03
number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416
这篇关于仅当需要科学记数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!