C# 如何在没有 10 次幂的情况下将 double 转换为字符串 (E-05)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1319191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert double to string without the power to 10 representation (E-05)
提问by Makach
How to convert double to string without the power to 10 representation (E-05)
如何在没有 10 次幂的情况下将 double 转换为字符串 (E-05)
double value = 0.000099999999833333343;
string text = value.ToString();
Console.WriteLine(text); // 9,99999998333333E-05
I'd like the string textto be 0.000099999999833333343 (or nearly that, I'm not doing rocket science:)
我希望字符串文本为 0.000099999999833333343(或者差不多,我不是在做火箭科学:)
I've tried the following variants
我尝试了以下变体
Console.WriteLine(value.ToString()); // 9,99999998333333E-05
Console.WriteLine(value.ToString("R20")); // 9,9999999833333343E-05
Console.WriteLine(value.ToString("N20")); // 0,00009999999983333330
Console.WriteLine(String.Format("{0:F20}", value)); // 0,00009999999983333330
Doing tostring N20 or format F20 seems closest to what I want, but I do end up with a lot of trailing zeros, is there a clever way to avoid this? I'd like to get as close to the double representation as possible 0.000099999999833333343
做 tostring N20 或格式 F20 似乎最接近我想要的,但我最终得到了很多尾随零,有没有聪明的方法来避免这种情况?我想尽可能接近双重表示 0.000099999999833333343
采纳答案by i_am_jorf
Use String.Format()with the format specifier. I think you want {0:F20} or so.
将String.Format()与格式说明符一起使用。我想你想要 {0:F20} 左右。
string formatted = String.Format("{0:F20}", value);
回答by Brian Rasmussen
Use string.Format
with an appropriate format specifier.
使用string.Format
具有适当的格式说明。
This blog post has a lot of examples: http://blogs.msdn.com/kathykam/archive/2006/03/29/564426.aspx
这篇博文有很多例子:http: //blogs.msdn.com/kathykam/archive/2006/03/29/564426.aspx
回答by Joel Coehoorn
You don't need string.Format()
. Just put the right format stringin the existing .ToString()
method. Something like "N" should do.
你不需要string.Format()
. 只需将正确的格式字符串放入现有.ToString()
方法中即可。像“N”这样的东西应该做。
回答by Zoman
How about
怎么样
Convert.ToDecimal(doubleValue).ToString()