2014-10-30 63 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上有很多帖子。只需在“浮点精度”或“精确浮点数”上进行表单搜索。