双变量值打印而不舍入 [英] double variable value print without rounding
问题描述
hi
double d = 123.45;
math.round(d,0).tostring();
但它打印124
i只想打印123而不是124
plz帮助。
你是非常错误的:舍入确实给你123,你的观察是错误的。
更重要的是:你应该明白,你不应该直接在这个和其他大多数情况下进行四舍五入。这有使用舍入值作为一些中间结果和失去精度的一些危险。相反,更喜欢使用格式化操作中嵌入的舍入:
string myOnScreenValue = string .Format( {0:###},d ); // 3个职位
string myOtherOnScreenValue = string .Format( {0:F0 },d); // 更好:小数部分的0位数
请参阅:
http:/ /msdn.microsoft.com/en-us/library/kfsatb94%28v=vs.110%29.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx [ ^ ],
http:// msdn .microsoft.com / zh-CN / library / 0c899ak8(v = vs.110).aspx [ ^ ]。
-SA
你可以使用Math.Truncate()
double d = 123 。 45 ;
var output = Math.Truncate(d).ToString();
更多信息: http://msdn.microsoft.com /en-us/library/c2eabd70(v=vs.110).aspx [ ^ ]
hi double d = 123.45;
math.round(d,0).tostring();
but it print 124
i want to print only 123 not 124
plz help.解决方案You are badly mistaken: rounding really gives you 123, not 124. Your observation was wrong.
More importantly: you should understand that you should not do rounding directly in this and most other cases. This has some danger of using rounded value as some intermediate result and loosing precision. Instead, prefer using rounding embedded in formatting operation:
string myOnScreenValue = string.Format("{0:###}", d); // 3 positions string myOtherOnScreenValue = string.Format("{0:F0}", d); // better: 0 digits in fractional part
Please see:
http://msdn.microsoft.com/en-us/library/kfsatb94%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx[^].
—SA
You can use Math.Truncate()
double d = 123.45; var output = Math.Truncate(d).ToString();
More at: http://msdn.microsoft.com/en-us/library/c2eabd70(v=vs.110).aspx[^]
这篇关于双变量值打印而不舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!