2014-12-21 20 views
2

我想知道如何獲得雙倍的小數部分。 我試着下面的代碼:如何檢查雙精度小數部分?

double auxValMin= Double.parseDouble("5.3"); 
double auxDecimal= auxValMin-floor(auxValMin); 
System.out.println(auxDecimal); //I get 0.2999999999999998 instead of 0.3 

我怎樣才能解決 「0.2999999999999998」?

+0

在這種情況下,您應該使用BigDecimal。看到這裏:http://stackoverflow.com/questions/3413448/double-vs-bigdecimal –

+1

如果你只想顯示小數部分,使用'split'並打印它作爲一個字符串。 – Maroun

+0

http://floating-point-gui.de/ –

回答

1

double精度更高,精度更高float但仍有舍入誤差。你必須圍繞任何你有一個理智的輸出的答案。

如果這不是需要的,你可以使用BigDecimal,它沒有舍入錯誤,但有它自己的頭痛恕我直言。

默認Float.toString()使用最小舍入,但通常它不夠。

System.out.println("With no rounding"); 
double n = 5.3d; 
System.out.println("n= "+new BigDecimal(n)); 
double expected = 0.3d; 
System.out.println("expected= "+new BigDecimal(expected)); 

System.out.println("n % 1= "+new BigDecimal(n % 1)); 
System.out.println("n - Math.floor(n) = "+new BigDecimal(n - Math.floor(n))); 
System.out.println("n - (int)n= "+new BigDecimal(n - (int)n)); 

System.out.println("With rounding"); 
System.out.printf("n %% 1= %.2f%n", n % 1); 
System.out.printf("n - Math.floor(n) = %.2f%n", n - Math.floor(n)); 
System.out.printf("n - (int)n= %.2f%n", n - (int)n); 

打印

With no rounding 
n= 5.29999999999999982236431605997495353221893310546875 
expected= 0.299999999999999988897769753748434595763683319091796875 
n % 1= 0.29999999999999982236431605997495353221893310546875 
n - Math.floor(n) = 0.29999999999999982236431605997495353221893310546875 
n - (int)n= 0.29999999999999982236431605997495353221893310546875 
With rounding 
n % 1= 0.30 
n - Math.floor(n) = 0.30 
n - (int)n= 0.30 

一個谷歌搜索有一點可能有幫助:https://stackoverflow.com/a/5017110/820410

1

現在每天的BigDecimal你會得到Java.Please閱讀和學習它有關的BigDecimal

BigDecimal value=new BigDecimal("5.36777777"); 
    System.out.println(value.round(new MathContext(2, RoundingMode.CEILING)));