Search code examples
javadoubleprecision

Losing precision when converting from inches to centimeter and vice versa


I am actually loosing precision values when I convert from Inches to Centimeter and Again Centimeter to Inches.

// Inches to Centimeter

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 );
}

// Centimeter to Inches

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;
}

If i enter 45, its showing 44.58. I don't know where the is the exact problem happening?


Solution

  • You have 0.39370 in one function and 0.39 in the other.

    The exact number of centimetres in 1 inch is 2.54.