,當它表示爲雙精度時略小於0.15。檢查了這一點
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.HALF_UP);
BigDecimal bd = new BigDecimal(0.15);
System.out.println("bd=" + bd);
System.out.println(df.format(0.15)); // expecting 0.1, getting 0.1
bd = new BigDecimal(0.05);
System.out.println("bd=" + bd);
System.out.println(df.format(0.05));
bd = new BigDecimal(0.06);
System.out.println("bd=" + bd);
System.out.println(df.format(0.06));
這段代碼的輸出是
bd=0.1499999999999999944488848768742172978818416595458984375
0.1
bd=0.05000000000000000277555756156289135105907917022705078125
0.1
bd=0.059999999999999997779553950749686919152736663818359375
0.1
一個可能的解決方案(如果你確實需要它來圓的正確方法)是使用BigDecimal.valueOf創造價值。例如
BigDecimal bd = BigDecimal.valueOf(0.15);
System.out.println("bd=" + bd);
System.out.println(df.format(bd)); // expecting 0.1, getting 0.1
bd = BigDecimal.valueOf(0.05);
System.out.println("bd=" + bd);
System.out.println(df.format(bd));
bd = BigDecimal.valueOf(0.06);
System.out.println("bd=" + bd);
System.out.println(df.format(bd));
現在將產生
bd=0.15
0.2
bd=0.05
0.1
bd=0.06
0.1
順便說一句,因爲可怕的袋熊指出,掩碼設定爲0.0,而不是#,#將0.6 0。但我認爲這是後來編輯然後當我開始看着它。使用 #。#。
that _is_ mysterious! – tofutim
也許你將不得不乘以10並再次除以變通方法 – tofutim
在1.7工作正常 也許看到http://stackoverflow.com/questions/22797964/is-inconsistency-in-rounding-between-java-7 -and-java-8-a-bug –