java 浮點數轉整數精度處理
阿新 • • 發佈:2018-11-29
System.out.println("------case1------"); BigDecimal bigDecimal = new BigDecimal(37.98); System.out.println(bigDecimal); //37.97999999999999687361196265555918216705322265625 System.out.println(bigDecimal.intValue()); //37 System.out.println("------case2------"); int totalAmount = (int) (37.98 * 100); System.out.println(totalAmount); //3797 System.out.println("------case3------"); totalAmount = new BigDecimal(37.98 * 100).intValue(); System.out.println(totalAmount); //3797 System.out.println("------case4------"); System.out.println(bigDecimal.movePointRight(2)); //3797.999999999999687361196265555918216705322265625 System.out.println(bigDecimal.movePointRight(2).intValue()); //3797 System.out.println("------case5------"); System.out.println(new BigDecimal(37).intValueExact()); //沒有異常,沒有小數點被擷取 37 //System.out.println(bigDecimal.intValueExact()); //存在異常,小數點精度丟失 System.out.println("------case6------"); System.out.println(bigDecimal.multiply(new BigDecimal(100))); //3797.99999999999968736119626555591821670532226562500 System.out.println(bigDecimal.multiply(new BigDecimal(100)).intValue()); //3797 //正確處理 System.out.println("------case7------"); System.out.println(new BigDecimal(37.9899).setScale(2, BigDecimal.ROUND_HALF_UP)); //保留兩位小數,後面小數上取整 37.99 System.out.println(bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue()); //3798 System.out.println(Math.ceil(37.98 * 100)); //37.98 * 100 = 3797.9999999999995 System.out.println((int) Math.ceil(37.98 * 100)); //3798
------case1------
37.97999999999999687361196265555918216705322265625
37
------case2------
3797
------case3------
3797
------case4------
3797.999999999999687361196265555918216705322265625
3797
------case5------
37
------case6------
3797.99999999999968736119626555591821670532226562500
3797
------case7------
37.99
3798
3797.9999999999995
3798.0
3798