截断在C#双重价值的数字数 [英] Truncate number of digit of double value in C#

查看:177
本文介绍了截断在C#双重价值的数字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能截断双重价值的前导数在C#中,我已经试过Math.Round(的doubleValue,2),但不给予需要的结果。我没有发现在数学课上任何其它方法。

How can i truncate the leading digit of double value in C#,I have tried Math.Round(doublevalue,2) but not giving the require result. and i didn't find any other method in Math class.

例如,我有值12.123456789,我只需要12.12。

For example i have value 12.123456789 and i only need 12.12.

推荐答案

编辑:它已经指出,这些方法的的价值,而不是的截断的。很难真正截断双击的价值,因为它不是真正的权利基地......但截断小数价值是比较可行的。

It's been pointed out that these approaches round the value instead of truncating. It's hard to genuinely truncate a double value because it's not really in the right base... but truncating a decimal value is more feasible.

您应该使用合适的格式字符串,可以的自定义标准,如:

You should use an appropriate format string, either custom or standard, e.g.

string x = d.ToString("0.00");

string x = d.ToString("F2");



这是值得意识到,一个双精度值本身并不知道有多少位小数有。当你将其转换为一个字符串,真的很有意义这样做,这只是。使用 Math.Round 将得到最接近的double值 x.xx00000 (如果你明白我的意思),但它几乎可以肯定不会是精确值 x.xx00000 由于道路二进制浮点类型的工作。

It's worth being aware that a double value itself doesn't "know" how many decimal places it has. It's only when you convert it to a string that it really makes sense to do so. Using Math.Round will get the closest double value to x.xx00000 (if you see what I mean) but it almost certainly won't be the exact value x.xx00000 due to the way binary floating point types work.

如果你需要这个东西的其他的不是字符串格式化,你应该考虑使用小数来代替。什么是值实际上代表了什么?

If you need this for anything other than string formatting, you should consider using decimal instead. What does the value actually represent?

我对二进制浮点点和十进制浮点在.NET点您可能会发现有用的。

I have articles on binary floating point and decimal floating point in .NET which you may find useful.

这篇关于截断在C#双重价值的数字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆