theJava theJava - 6 months ago 9
Java Question

Strange issue in converting Feet and Inches to Centimeter and Vice Versa

public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {

}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}


Above is the function for converting Feet and Inches to Centimeter.Below is the function for converting Centimeter back to Feet and Inches.

public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}


I have a problem when i enter normal values like
5 Feet and 6 Inches
, its converting perfectly to centimeter and again it gets converted back to 5 Feet and 6 Inches.


The Problem is when i convert 1 Feet and 1 inches or 2 Feet and 2
inches, its getting converted back to 1 Feet 2 inches and 2 Feet 3
inches.

Answer

I believe:

inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));

Should be:

inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));