从英寸转换为厘米时失去精度,反之亦然

时间:2013-06-10 15:06:33

标签: java double precision

当我从Inches to Centimeter和再次Centimeter to Inches转换时,我实际上正在丢失精度值。

//英寸到厘米

public static String convertInchesToCentimeter(String inches) {
    double in = 0;
    try {
        if (inches != null && inches.trim().length() != 0) { in = Double.parseDouble(inches) / 0.39370;
        }
    } catch (NumberFormatException nfx) {
        System.err.println("Invalid input.");
    }
    return String.valueOf( in );
}

//厘米到英寸

public static double convertCentiToInch(double d) {
    double centiToInch = 0;
    if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {

        centiToInch = d * 0.39;
    }
    return centiToInch;
}

如果我输入45, its showing 44.58。我不知道究竟发生了什么问题?

2 个答案:

答案 0 :(得分:6)

你在一个函数中有0.39370而在另一个函数中有0.39。

完全号是1英寸是2.54厘米。

答案 1 :(得分:0)

一个可能的问题是您在一个函数中使用0.39370,而在另一个函数中使用.39。我建议使用2.54厘米每英寸的确切值。

即使有这种变化,浮点数通常也是不精确的。

相关问题