且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将double值舍入为2个小数点?

更新时间:2023-12-03 15:56:04

2和2.00之间的内部表示没有区别。您可以使用 Math.round 将值舍入到最接近的整数 - 将该轮舍入到2位小数,您可以乘以100,舍入,然后除以100,但由于二进制浮点运算的性质,你不应该期望结果完全 2dps。

There's no difference in internal representation between 2 and 2.00. You can use Math.round to round a value to the nearest integer - to make that round to 2 decimal places you could multiply by 100, round, and then divide by 100, but you shouldn't expect the result to be exactly 2dps, due to the nature of binary floating point arithmetic.

如果你只是感兴趣格式化一个值到两位小数,请看 DecimalFormat - 如果您对计算时的多个小数位感兴趣,那么您应该使用 的BigDecimal 。这样你就会知道你真的在处理十进制数字,而不是最近的可用 double 值。

If you're only interested in formatting a value to two decimal places, look at DecimalFormat - if you're interested in a number of decimal places while calculating you should really be using BigDecimal. That way you'll know that you really are dealing with decimal digits, rather than "the nearest available double value".

如果您总是处理两位小数,您可能需要考虑的另一个选项是将值存储为 long BigInteger ,知道它恰好是真实值的100倍 - 例如,有效地存储美分而不是美元。

Another option you may want to consider if you're always dealing with two decimal places is to store the value as a long or BigInteger, knowing that it's exactly 100 times the "real" value - effectively storing cents instead of dollars, for example.