我通过移植一些传统的C++代码来获取C#,并希望保持输出相同.曾经是过去的东西
output << std::setprecision(10) << (double) value;
Run Code Online (Sandbox Code Playgroud)
我想现在会
output.Write("{0:F10}", value);
Run Code Online (Sandbox Code Playgroud)
但这并没有成功.特别是值> 1会得到更多的数字.一个常见的在线建议是Math.Round首先,但如果总长度为零,则会附加零< 10.
所以我把它放在一起:
// std::setprecision is not exactly the same as ":F10", mirror original behavior
static string setPrecision(double value) {
string ret = value.ToString();
// Don't just Substring(0, 11), we need to apply rounding,
// and don't always do this, we don't want to append zeroes,
// for 10 digits + period, with 0.. not counting for total
if(ret.Length > digits + 1)
ret = Math.Round(value, digits + (value < 1 ? 1 : 0) - ret.IndexOf('.')).ToString();
return ret;
}
Run Code Online (Sandbox Code Playgroud)
其中digits是静态常数; 我当然可以把它变成一个变量,但对于这个项目来说,这样做是没有意义的.
尽管如此,这似乎过于复杂.是否有更优雅的方式来获得传统行为?
根据要求提供一些示例I/O.
// C++
double test = 0; out << std::setprecision(10);
test = 0.123456780; out << test << '\n';
test = 0.0123456781; out << test << '\n';
test = 0.11234567819; out << test << '\n';
test = 1.00234567899; out << test << '\n';
// C#
double test = 0;
test = 0.123456780; output.WriteLine(setPrecision(test));
test = 0.0123456781; output.WriteLine(setPrecision(test));
test = 0.11234567819; output.WriteLine(setPrecision(test));
test = 1.00234567899; output.WriteLine(setPrecision(test));
Run Code Online (Sandbox Code Playgroud)
两者都产生:
0.12345678
0.0123456781
0.1123456782
1.002345679
Run Code Online (Sandbox Code Playgroud)
同时我注意到所有标题零点似乎都不计入总数而不仅仅是第一个;
// C++
test = 0.012345678906; out << test << '\n'; // 0.01234567891
test = 0.0012345678906; out << test << '\n'; // 0.001234567891
test = 0.00012345678906; out << test << '\n'; // 0.0001234567891
// C#
test = 0.012345678906; output.WriteLine(setPrecision(test)); // 0.0123456789
test = 0.0012345678906; output.WriteLine(setPrecision(test)); // 0.0012345679
test = 0.00012345678906; output.WriteLine(setPrecision(test)); // 0.0001234568
Run Code Online (Sandbox Code Playgroud)
如果没有更简单的解决方案,我将不得不纠正.
小智 6
听起来您只想打印具有特定有效位数的数字.您只需使用G格式字符串指定要使用的位数即可.
output.Write("{0:G10}", value);
Run Code Online (Sandbox Code Playgroud)