我正在修补Android中的BigDecimal
和货币格式,并想知道是否可以使用BigDecimal
执行以下操作:
我想要的是什么:
64.99 --> 65.00 (Rounded Up)
64.99 --> 60.00 (Rounded Down)
65.01 --> 70.00 (Rounded Up)
65.01 --> 65.00 (Rounded Down)
目前,根据我的代码,我只能舍入到零。例如:
我得到了什么:
64.99 --> 70.00 (Rounded Up)
64.99 --> 60.00 (Rounded Down)
65.01 --> 70.00 (Rounded Up)
65.01 --> 60.00 (Rounded Down)
有没有办法使用BigDecimal
来实现我的目标?
我的代码:
private static void printRoundedValues() {
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
BigDecimal valueUp = new BigDecimal(64.50, new MathContext(1,RoundingMode.UP));
BigDecimal valueDown = new BigDecimal(64.50, new MathContext(1,RoundingMode.DOWN));
System.out.println("Value Up: " + currencyFormat.format(valueUp));
System.out.println("Value Down: " + currencyFormat.format(valueDown));
}
答案 0 :(得分:4)
您可以乘以2
,然后四舍五入到最近的10
,然后除以2
。这些2
的精确度为BigDecimals
;对于不同规模的BigDecimals
,它可能需要不同。
BigDecimal[] bds = {new BigDecimal("64.99"), new BigDecimal("65.01")};
BigDecimal two = new BigDecimal("2");
MathContext mcUp = new MathContext(2, RoundingMode.UP);
MathContext mcDown = new MathContext(2, RoundingMode.DOWN);
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (BigDecimal bd : bds)
{
System.out.println("Test: " + bd);
BigDecimal roundUp5 = bd.multiply(two).round(mcUp).divide(two);
System.out.println("Round up: " + currency.format(roundUp5));
BigDecimal roundDown5 = bd.multiply(two).round(mcDown).divide(two);
System.out.println("Round down: " + currency.format(roundDown5));
}
输出:
Test: 64.99
Round up: $65.00
Round down: $60.00
Test: 65.01
Round up: $70.00
Round down: $65.00
答案 1 :(得分:0)
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
BigDecimal valueUp = new BigDecimal(64.50, new MathContext(2, RoundingMode.UP));
BigDecimal valueDown = new BigDecimal(64.50, new MathContext(2, RoundingMode.DOWN));
System.out.println("Value Up: " + currencyFormat.format(valueUp));
System.out.println("Value Down: " + currencyFormat.format(valueDown));
以下是MathContext精度的工作原理:
您可能需要设置比例而不是精确度:
BigDecimal valueUp = new BigDecimal(64.50).setScale(0, RoundingMode.UP);
BigDecimal valueDown = new BigDecimal(64.50).setScale(0, RoundingMode.DOWN);
答案 2 :(得分:0)
您正在寻找的功能是setScale,它是BigDecimal的一部分。
以下是对同一问题的一个很好的答案: Java BigDecimal: Round to the nearest whole value