这是我们尝试过的方法,但这些方法都不起作用......
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,但这不起作用
最佳答案
TL;DR:使用 BigDecimal.ROUND_HALF_UP
作为舍入模式和/或使用字符串作为输入而不是 double 来创建 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.
VS。你用过什么。
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.
你总是四舍五入。并且您有一个带有小数位的数字要舍入,因为您使用 double 作为输入来创建 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.
此外,您应该从字符串输入而不是 double 创建 BigDecimals。在构造函数中的值上使用引号 "
。
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
double 在每个十进制数字上并不具有完美的精度,而字符串则具有完美的精度。
关于java - 将 java BigDecimal 中的 6.51 更改为 6.50,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936527/