有 Java 编程相关的问题?

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

Java四舍五入BigDecimal值,在2个级别保留2位小数

decimalValue=10.2345在使用下面的代码进行舍入后给出10.23

decimalValue.setScale(2, RoundingMode.HALF_UP)

我需要将值显示为10.24。找到了一种在两个级别进行舍入的解决方案,例如先舍入到3位数,然后舍入到2位数,如下所示

decimalValue.setScale(3, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP)

请建议是否有更好的解决方案


共 (1) 个答案

  1. # 1 楼答案

    RoundingMode.HALF_UP将对.5及以上的数据进行汇总

    HALF_UP

    Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for RoundingMode.UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for RoundingMode.DOWN.

    改用RoundingMode.UP

    decimalValue.setScale(2, RoundingMode.UP)