我正在尝试在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));
}

最佳答案

您可以乘以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

10-06 12:42