[英]Apply multiple numeric formatting simultaneously, C#
Is it possible to apply multiple formatting simultaneously to a double? 是否可以将多个格式同时应用于double?
For example, I want something like this 例如,我想要这样的东西
double d = 1234.567;
string format = ?
// sig digit 4 , digit after decimal 4 , format = combination of G4 and F4 , G4F4?
d.toString(format) => "1235.0000"
Here, "G4" limits the significant digits to 4 and "F4" determines the number of digits after decimal point. 在此,“ G4”将有效数字限制为4,“ F4”确定小数点后的位数。
I know it is possible by using 2 separate format 我知道可以通过使用2种单独的格式
Double.Parse((1234.567).ToString("G4")).ToString("F4") => "1235.0000"
Some more example 一些更多的例子
//sig digit 3 , digit after decimal 0 , format = combination of G3 and F0
d.toString(format) => "1230"
//sig digit 8 , digit after decimal 8 , format = combination of G8 and F8
d.toString(format) => "1234.56700000"
//sig digit 1 , digit after decimal 1 , format = combination of G1 and F1
d.toString(format) => "1000.0"
Your format string doesn't really make any sense. 您的格式字符串实际上没有任何意义。 Significant digits can be before or after the decimal point; 有效数字可以在小数点之前或之后; you're trying to specify two overlapping and contradictory formats simultaneously. 您正在尝试同时指定两种重叠且矛盾的格式。
I think you are looking for: ToString("0.0000")
我认为您正在寻找: ToString("0.0000")
I think your question is about Standard Numeric Format Strings , then you should follow its specifications, else you will get a FormatException
as noted at the end of table: 我认为您的问题是关于Standard Numeric Format Strings的 ,那么您应该遵循其规范,否则您将获得FormatException
如表尾所示:
Any other single character | 其他任何单个字符| Unknown specifier | 未知说明符| Result: Throws a
FormatException
at run time. 结果:在运行时引发FormatException
。
What about using an extension method like this: 如何使用这样的扩展方法:
public static string ToString(this double value, int sig)
{
return double.Parse(value.ToString($"G{sig}")).ToString($"F{sig}");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.