gpt4 book ai didi

android - BigDecimal 舍入为 0 或 5

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:04:51 25 4
gpt4 key购买 nike

我正在修改 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。这些 BigDecimals 的精度为 2;对于不同比例的 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

关于android - BigDecimal 舍入为 0 或 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21887385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com