有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java BigDecimal中的十进制更改6.51到6.50

这就是我们尝试过的,但这些都不起作用

BigDecimal Total_Discount=new BigDecimal(10.00); 
BigDecimal Amount_To_User=new BigDecimal(00.00); 
BigDecimal Amount_To_Me=new BigDecimal(00.00);          

Amount_To_User=Total_Discount.multiply(new BigDecimal(0.65)).setScale(2,BigDecimal.ROUND_UP); //65% of the amount
Amount_To_Me=Total_Discount.multiply(new BigDecimal(0.35)).setScale(2,BigDecimal.ROUND_UP); //35% of the amount

Dividing the values by % 65 and 35 so 10 will be 6.50 and 3.50 but i am getting 6.51 by using BigDecimal.DOWN i am getting 6.50 i have already values with 6.51 which i need to change to 6.50

Amount_To_User=Amount_To_User.setScale(2, BigDecimal.ROUND_CEILING);
System.out.println(Amount_To_User); //Gives the value 6.51

我想把6.51改成6.50,但这行不通


共 (1) 个答案

  1. # 1 楼答案

    TL;DR:使用BigDecimal.ROUND_HALF_UP作为舍入模式和/或使用字符串作为输入而不是双精度来创建一个BigDecimal

    解释

    比较文档。以下是你想要的:

    BigDecimal.ROUND_HALF_UP

    Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.

    与你用过的相比

    BigDecimal.ROUND_CEILING (in your case behaves like BigDecimal.ROUND_UP, see below)

    Rounding mode to round towards positive infinity. If the BigDecimal is positive, behaves as for ROUND_UP; if negative, behaves as for ROUND_DOWN. Note that this rounding mode never decreases the calculated value.

    你总是围着我转。还有一个需要舍入的小数位,因为您使用双精度作为输入来创建BigDecimal(参见下面的示例)

    BigDecimal.ROUND_UP

    Rounding mode to round away from zero. Always increments the digit prior to a nonzero discarded fraction. Note that this rounding mode never decreases the magnitude of the calculated value.

    此外,您应该根据字符串输入而不是双精度输入创建大小数。对构造函数中的值使用引号"

    BigDecimal total_Discount = new BigDecimal("10.00");
    BigDecimal amount_To_User = new BigDecimal("00.00");
    BigDecimal amount_To_Me = new BigDecimal("00.00");
    
    amount_To_User = total_Discount.multiply(new BigDecimal("0.65")).setScale(2, BigDecimal.ROUND_HALF_UP);
    amount_To_Me = total_Discount.multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(amount_To_User); //6.50
    System.out.println(amount_To_Me); //3.50
    

    这将告诉你为什么:

    System.out.println(new BigDecimal(0.65));
    //prints 0.65000000000000002220446049250313080847263336181640625
    System.out.println(new BigDecimal("0.65"));
    //prints 0.65
    

    当字符串具有双精度时,双精度并非对每个十进制数字都有完美的精度