仅用两个小数舍入一个双精度值 [英] Round a double value with two decimals only

查看:119
本文介绍了仅用两个小数舍入一个双精度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我需要将一个双精度值四舍五入到两个小数位.

我需要做的.

例如

x = 7.3256

我需要在x = 7.33
中转换x
如何在C#代码中做到这一点.

在此先感谢

Hello Everybody

I need to round a double value with two decimal places.

What I need to do that.

for example

x=7.3256

I need convert x in x=7.33

How I can do that in c# code.

Thanks in advance

推荐答案

这应该可以解决问题:
This should do the trick:
x = Math.Round(x, 2);


注意!确定要舍入吗?



很有可能,您根本不需要四舍五入.

四舍五入本身几乎不应该使用(排除是罕见的而且非常先进:在随机数生成,密码学中……).最有可能的是,当转换为字符串输出时,只需要对图形进行四舍五入即可.实际上,这是不同的.您只需要正确的字符串格式即可:

Caution! Are you sure you need rounding?



Chances are, you don''t need rounding at all.

Rounding per se should almost never be used (exclusions are rare and very advanced: in random number generation, cryptography...). Most probably, you only need rounded look of the figures when converted to string for output. In practice, this is different. All you need is proper string formatting:

System.Console.WriteLine("{0:G3}", myDoublePrecisionNumber);




or

string output = 
   string.Format("{0:G3}", myDoublePrecisionNumber);



要获取更多帮助,请键入string.Format,在格式"上按F1并阅读Microsoft帮助-所有您需要的信息.
除非确实需要,否则不要弄乱取整.



For further help, type string.Format, press F1 on Format and read Microsoft help -- all you need.
Don''t mess with rounding unless it is really needed.


这篇关于仅用两个小数舍入一个双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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