2014-10-30 60 views
0

我有浮動轉換爲字符串「錯誤」和浮動

total = quant * valUnit; 

lb_total.setText(String.format(Locale.US,"%.2f", total)); 

if total = 56.025(7.5 * 7.47) > 56.02 

if total = 71.025(7.5 * 9.47) > 71.03 

爲什麼第一輪沒有一個代碼?

我找到了解決方案,我的問題,我創建一個類,使其正確。

import java.lang.Math; 

// iniF = value to be rounded 
// posIni = number of max houses(EX: 7.45 * 7.999, max houses for this operation is five) 
// posFin = number of houses after rounded 
// EX: xx*.xxxxx -> xx*.xx posIni = 5, posFin = 2 
public class MyMath { 
    public Float MyRound(Float iniF, int posIni, int posFin){ 
     Float result  = 0.00f; 
     int resultTmp = 0; 
     int nCasas  = (int) Math.pow(10, posIni - 1); 
     Float arredondaF = iniF * nCasas; 

     for(int p = posIni; p > posFin; p--){ 
      resultTmp = Math.round(arredondaF); 
      arredondaF = (float) resultTmp/10; 
     } 

     result = arredondaF/10; 

     return result; 
    } 
} 

回答

1

這是由於內部精度差異,尤其是因爲這些數字是浮點運算的結果。在內部,56.025實際上是類似於56.0249999998,並且71.025類似71.025000000002。由於二進制/十進制轉換和值的位分辨率,浮點運算在計算機中不完全精確。從紅寶石採取

下面舉例來說明:

irb(main):003:0> format("%.2f", 7.5 * 7.47) 
=> "56.02" 
irb(main):004:0> format("%.2f", 7.5 * 9.47) 
=> "71.03" 

在這裏,我使用的格式的更高的精度,你可以看到什麼樣的價值觀真的是:

irb(main):007:0> format("%.15f", 7.5 * 9.47) 
=> "71.025000000000006" 
irb(main):008:0> format("%.15f", 7.5 * 7.47) 
=> "56.024999999999999" 

有關於這個問題,在各種形式的stackoverflow.com上有很多帖子。只需在「浮點精度」或「精確浮點數」上進行表單搜索。