![](/img/trans.png)
[英]String.Format decimal with both thousand separators and forced decimal places
[英]Specify decimal places for all placeholders with String.Format
使用String.Format
语法,我知道我可以格式化具有小数位数的double
,如下所示:
String.Format("{0:F8}", 0.123456789);
在大多数情况下都可以,但是我正在编写一个函数,其中调用函数应指定格式字符串。 格式字符串指定函数与外部程序交互的方式。 需要高精度,因此所有double
需要格式化为小数点后8位。 为了将接口与实现分开,我不能期望调用函数理解精度的要求,因此不能期望格式字符串在格式字符串中包含小数点说明符。
我当前的最佳选择是仅使用正则表达式修改格式字符串。 有没有一种更干净的方法来指定所有由String.Format
格式化的double
都应具有这种精度?
通常使用以下两个参数调用该函数:
"new Generator.{0} bus1={1} phases=3 model=1 status=fixed kV={2} Vminpu=0.5 Vmaxpu=2kW=0 kvAR={3}"
为什么不为double
创建扩展方法? 它应该返回字符串转换double
-格式化你想(8位小数)的精度。 这样,调用函数就可以只指定格式字符串了。.没有别的..不需要指定数字精度。
就像是:
static string ToPreciseString(this double data)
{
return String.Format("{0:F8}", data);
}
因此,您要创建的功能可以是:
void MyFunction(string stringFormatWithoutPrecision)
{
double anyDoubleValue; //i dont know where you get the double data from
string formattedData = String.Format(stringFormatWithoutPrecision, anyDoubleValue.ToPreciseString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.