2016-09-23 26 views
-1

我很驚訝看到下面的程序,請告知它如何表現如此,因爲我非常認同poitn精確到小數點後,下面是progrmam小數點精度丟失對於一些雙數據類型的情況下的某些munbers

double fixedRate = 0.997500000000; //**output --->0.9975 
    // BigDecimal fixedRate = new BigDecimal("0.997500000000");   
     double fixedRate1 = 0.123456789; 

     System.out.println(fixedRate); 
     System.out.println(fixedRate1); 

和輸出

0.9975 
0.123456789

現在請大家指教爲先輸出中是0.9975,但尾盤爲下它不是小數點後截斷,但爲什麼第一次呢。

+0

看一看教程就如何格式化數字https://docs.oracle.com/javase/tutorial/java/data /numberformat.html – Kennet

+0

沒有那是不同的事我同意謝謝你的建議 – user1508454

+1

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html閱讀並重讀,直到你完全理解 – jwenting

回答

0
This is a printing problem.Please use this format to print your values and tell me the result: 

double fixedRate = 0.997500000000; 
double fixedRate1 = 0.123456789; 

System.out.println(String.format("%.19f", fixedRate)); 
System.out.println(String.format("%.19f", fixedRate1)); 

Good Luck ! 
+0

沒有靜止不工作的輸出是1.00, 0.12 – user1508454

+0

@ user1508454 ..請使用: System.out.println(String.format(「%。19f」,fixedRate)); System.out.println(String.format(「%。19f」,fixedRate1)); –

+0

@ user1508454 ..這意味着你應該根據自己的意願設置deciminal地方。例如。%。2f,%3.f,%4.f,對於你的情況,我認爲它是%19.f。 –

0

精度不是丟失。它只是沒有打印,因爲你不需要更多的數字來區分打印值和其他任何double值。

如果你想強制某個小數位數,看看System.out.printf()的String.format()

有關更多詳情和可能的格式,請參閱https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

結果可能是這樣的:

  System.out.printf("%.19f%n",fixedRate); 
      System.out.printf("%.19f%n", fixedRate1); 
0

根據你的問題

爲先輸出中是0.9975,但尾盤爲下它不是 小數點但爲什麼後截斷首先

由於double是數字數據類型,因此不能保持領先和t欄杆零。

A double不關心格式化 - 只是關於存儲。打印時,它會轉換爲字符串(使用Double的靜態toString方法)。

簡而言之,值0.99750.997500000000沒有區別,或者它與0.997500000000相同,因爲數字沒有任何值。

但考慮如果你有這樣的價值0.9975000000001那麼所有的數字將被打印。檢查它here

如果要格式化的值,那麼你可以看到這樣一個問題:How to properly display a price up to two decimals (cents) including trailing zeros in Java?