[英]Java Math RoundingMode.HALF_EVEN different results
看起來HALF_EVEN
舍入模式在Java DecimalFormat
與BigDecimal
。 有沒有辦法讓DecimalFormat
保持一致?
// Using BigDecimal scale
System.out.println("Big decimal scale (HALF_EVEN) of 21.255 ==> " + new BigDecimal("21.255").setScale(2, RoundingMode.HALF_EVEN));
System.out.println("Big decimal scale (HALF_EVEN) of 21.265 ==> " + new BigDecimal("21.265").setScale(2, RoundingMode.HALF_EVEN));
// Using DecimalFormat
DecimalFormat cdf = new DecimalFormat("#,##0.00");
cdf.setRoundingMode(RoundingMode.HALF_EVEN); // default anyway
System.out.println("Decimal format (HALF_EVEN) of 21.255 ==> " + cdf.format(21.255));
System.out.println("Decimal format (HALF_EVEN) of 21.265 ==> " + cdf.format(21.265));
Output:
Big decimal scale (HALF_EVEN) of 21.255 ==> 21.26
Big decimal scale (HALF_EVEN) of 21.265 ==> 21.26
Decimal format (HALF_EVEN) of 21.255 ==> 21.25
Decimal format (HALF_EVEN) of 21.265 ==> 21.27
如評論中所述,如果您嘗試:
Double double1 = new Double(21.255);
BigDecimal bigDecimal1 = new BigDecimal(double1);
System.out.println(bigDecimal1); //21.254999999999999005240169935859739780426025390625
Double double2 = new Double(21.265);
BigDecimal bigDecimal2 = new BigDecimal(double2);
System.out.println(bigDecimal2); //21.2650000000000005684341886080801486968994140625
你會發現:
double 21.255
略低於21.255
double 21.265
略高於21.265
您可以在使用DecimalFormat
時將輸入作為BigDecimal
啟動,以避免丟失准確性:
System.out.println("Decimal format (HALF_EVEN) of 21.255 ==> " + cdf.format(new BigDecimal("21.255")));
//21.26
System.out.println("Decimal format (HALF_EVEN) of 21.265 ==> " + cdf.format(new BigDecimal("21.265")));
//21.26
我剛剛進行了一些測試:使用@Mark Rotteveel解決方案:
cdf.format(new BigDecimal(21.255))
Big decimal scale (HALF_EVEN) of 21.255 ==> 21.26
Big decimal scale (HALF_EVEN) of 21.265 ==> 21.26
Decimal format (HALF_EVEN) of 21.255 ==> 21,25
Decimal format (HALF_EVEN) of 21.265 ==> 21,27
使用BigDecimal
String構造函數:
cdf.format(new BigDecimal("21.255"))
Big decimal scale (HALF_EVEN) of 21.255 ==> 21.26
Big decimal scale (HALF_EVEN) of 21.265 ==> 21.26
Decimal format (HALF_EVEN) of 21.255 ==> 21,26
Decimal format (HALF_EVEN) of 21.265 ==> 21,26
很明顯,您必須使用String
構造函數來獲得正確的結果
雙21.255
值不完全是21.255,它實際上更接近21.25499999...
,這意味着即使使用舍入模式HALF_EVEN
,它也會向下舍入到21.25
。 同樣,雙21.265
實際上更接近21.26500000000000056...
這意味着它將向上舍入。
通過使用new BigDecimal(double)
而不是new BigDecimal(String)
您可以獲得與DecimalFormat
完全相同的行為
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.