BigDecimal Rounding modes

此生再无相见时 提交于 2019-12-24 10:51:02

问题


We are replacing some sybase code to Java and having issue with Rounding BigDecimal to match what sybase returns

11.4443999999999999062083588796667754650115966796875 - Should return 11.44

and

35.9549999999999982946974341757595539093017578125 - should return 35.96

I have tried all different rounding options with scale set to 2, but none works for both. What is the best option?


回答1:


You'll have to take a two-step approach. First round to scale 3, then to scale 2, using RoundingMode.HALF_UP:

BigDecimal value1 = new BigDecimal("11.4443999999999999062083588796667754650115966796875");      
BigDecimal value2 = new BigDecimal("35.9549999999999982946974341757595539093017578125"); 

BigDecimal rounded1 = value1.setScale(3, RoundingMode.HALF_UP); // 11.444
rounded1 = rounded1.setScale(2, RoundingMode.HALF_UP);          // 11.44

BigDecimal rounded2 = value2.setScale(3, RoundingMode.HALF_UP); // 35.955
rounded2 = rounded2.setScale(2, RoundingMode.HALF_UP);          // 35.96



回答2:


This solution is not efficient but it gets the job done.

Source code

import java.math.BigDecimal;

public class BigDecimalRound {
    public static void main(String[] args) {
        BigDecimal bd;
        float f;

        bd = new BigDecimal(11.4443999999999999062083588796667754650115966796875);
        f = roundBigDecimal(bd, 2);
        System.out.println("bd: " + bd + ", f: " + f);

        bd = new BigDecimal(35.9549999999999982946974341757595539093017578125);
        f = roundBigDecimal(bd, 2);
        System.out.println("bd: " + bd + ", f: " + f);
    }

    public static float roundBigDecimal(BigDecimal bd, int precision) {
        int i = (int) Math.pow(10, precision);
        return (float) Math.round(bd.floatValue() * i) / i;
    }
}

Output

bd: 11.4443999999999999062083588796667754650115966796875, f: 11.44
bd: 35.9549999999999982946974341757595539093017578125, f: 35.96


来源:https://stackoverflow.com/questions/54059564/bigdecimal-rounding-modes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!