限制双到3位小数 [英] Limiting double to 3 decimal places

查看:132
本文介绍了限制双到3位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这我什么,我想实现:

如果一个双有超过3位小数,我要截断超出第三任小数。 (不圆)。

If a double has more than 3 decimal places, I want to truncate any decimal places beyond the third. (do not round.)

Eg.: 12.878999 -> 12.878

如果一个双少于3位小数,保留不变

If a double has less than 3 decimals, leave unchanged

Eg.:   125   -> 125
       89.24 -> 89.24

我碰到这个命令传来:

I came across this command:

double example = 12.34567;
double output = Math.Round(example, 3);

但我并不想圆。根据上面张贴的命令,
12.34567 - > 12.346

我要截断的价值,使之成为: 12.345

I want to truncate the value so that it becomes: 12.345

推荐答案

双打没有小数位 - 他们不是基于十进制数字开始。 当截断为三个十进制数字最接近双倍于当前值,你可以得到,但它仍然不会是完全一样的。你会更好使用小数

Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.

话说回来,如果是只有四舍五入发生,这是一个问题,你可以使用 Math.Truncate(值* 1000)/ 1000的方式; 其中的可以的做你想做的。 (你不想的四舍五入的根本,通过它的声音。)它仍然是潜在的狡猾,虽然,因为结果仍然不会真的只是小数点后三位。如果你做同样的事情用一个十进制值,但是,它的的工作:

Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:

decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878

编辑:LBushkin指出的那样,你应该截断了的显示的目的(这通常可在格式说明来完成),并截断了进一步的计算(在这种情况下,上面应该工作之间的明确)。

As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).

这篇关于限制双到3位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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