简体   繁体   English

Java - 将双精度舍入到小数点后 2 位

[英]Java - rounding double to 2 decimal places

I know this question has been asked many times but I'm stuck and I don't know what the correct solution should be.我知道这个问题已被问过很多次,但我被困住了,我不知道正确的解决方案应该是什么。 I'm writing a program and there's a lot of numbers multiplication.我正在编写一个程序,并且有很多数字乘法。 The result must be rounded to 2 decimal places but sometimes the result is not correct.结果必须四舍五入到小数点后 2 位,但有时结果不正确。

For example: I have two doubles v1=99.338 and v2=732.5.例如:我有两个双打 v1=99.338 和 v2=732.5。

I want to multiply them and have the result rounded to 2 decimal places.我想将它们相乘并将结果四舍五入到小数点后 2 位。 The correct result is 72765.085 so after rounding it should be 72765.09 however in computer the result is 72765.08499999999 and all the rounding methods give 72765.08 which is obviously wrong.正确的结果是 72765.085 所以四舍五入后它应该是 72765.09 但是在计算机中结果是 72765.08499999999 并且所有的四舍五入方法都给出了 72765.08 这显然是错误的。

For example例如

double x= v1 * v2; //x=72765.08499999999

    DecimalFormat dec= new DecimalFormat("0.00");
    decsetRoundingMode(RoundingMode.HALF_UP);
    String v = dec.format(x);

gives 72765.08.给出 72765.08。 The RoundingMode.CEILING in this example works OK but with other values for v and v2 is wrong.此示例中的 RoundingMode.CEILING 工作正常,但 v 和 v2 的其他值是错误的。

NumberFormat nf= NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.format(x);

gives 72765.08.给出 72765.08。

BigDecimal big = new BigDecimal(x, setScale(2, RoundingMode.HALF_UP);
double v = decWartosc.format(x);

gives v=72765.08.给出 v=72765.08。 Any other ideas?还有其他想法吗?

I've tried this in C# and the result is correct.我在 C# 中试过这个,结果是正确的。

You must use BigDecimal for the calculation itself.您必须使用BigDecimal进行计算本身。

BigDecimal exact = BigDecimal.valueOf(v1).multiply(BigDecimal.valueOf(v2));
BigDecimal big = exact.setScale(2, RoundingMode.HALF_UP);
System.out.println(big.toString());

First of all 99.337 * 732.5 = 72764.3525 , and NOT 72765.085 .首先99.337 * 732.5 = 72764.3525 ,而NOT 72765.085

Now, this code:现在,这段代码:

BigDecimal b1 = new BigDecimal("99.337");
BigDecimal b2 = new BigDecimal("732.5");
BigDecimal result = b1.multiply(b2).setScale(2, RoundingMode.HALF_UP);
System.out.println(result);

Outputs:输出:

72764.35

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM