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.
I ran the following code
public class FeetInches{
public static void main(String[] args){
double d = convertFeetandInchesToCentimeter("1","1");
String back_again = convertCentimeterToHeight(d);
System.out.println(back_again);
}
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);
}
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);
System.out.println((d / 2.54) - (feetPart * 12));
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
}
And got
1.0000000000000018
1' 2''
By using the ceiling function you are rounding up to 2 when you really want to be rounding down to 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With