Rahul Vyas
Rahul Vyas

Reputation: 28740

convert centimeter to feet and inches and vice versa different output?

I am using following code to convert centimeters into feet and inches but it doesn't work as expected.

+ (NSString*)getfeetAndInches:(float)centimeter {
    float totalHeight = centimeter * 0.032808;
    float myFeet = (int)totalHeight; //returns 5 feet
    float myInches = fabsf((totalHeight - myFeet) * 12);
    NSLog(@"%f",myInches);


    return [NSString stringWithFormat:@"%d' %0.0f\"",(int)myFeet,roundf(myInches)];
}

I'm using the following code to convert feet and inches string into centimeter

NSInteger totalInches = ([self.Feets integerValue] * 12) + [self.Inches integerValue];

            self.heightInCm = totalInches * 2.54;

But when I convert self.heightInCm back to feet and inches it does not provide correct value.Could someone post a perfect working example of this

Upvotes: 5

Views: 7653

Answers (2)

KevinB
KevinB

Reputation: 2484

This is the Swift version, to convert centimeters to feet and inches:

SWIFT 4

func showFootAndInchesFromCm(_ cms: Double) -> String {

      let feet = cms * 0.0328084
      let feetShow = Int(floor(feet))
      let feetRest: Double = ((feet * 100).truncatingRemainder(dividingBy: 100) / 100)
      let inches = Int(floor(feetRest * 12))

      return "\(feetShow)' \(inches)\""
}

Upvotes: 5

Sulthan
Sulthan

Reputation: 130152

In general, your code works correctly. There are some minor issues, e.g. the fabsf is not necessary but from my testing it works well.

The problem you have is probably caused by the fact, that when converting to feets and inches, you are rounding off values.

An inch is equal to 2.54 cm. If you are rounding inches to an integer value, your maximum precision will be 2.54 cm.

For example, 5'11' is 180,3 cm. 6'0 is 182,8cm. Anything between those two values (e.g. 181, 182, 183 will get rounded to either 5'11 or 6'0).

The correct solution depends on your use case. If you are only presenting the values to the user, keep them in centimeters and only convert to feet&inches when displaying. If your users are entering the value, you can't make it more precise but you can accept/display inches as a decimal value (replace roundf(myInches) with just myInches and use [self.inches floatValue]).

From the comments, you also have a rounding problem when inches calculated as 11.8 are rounded up to 12 which doesn't make sense in the result. I recommend to rework the algorithm into the following:

const float INCH_IN_CM = 2.54;

NSInteger numInches = (NSInteger) roundf(centimeter / INCH_IN_CM);
NSInteger feet = numInches / 12;
NSInteger inches = numInches % 12;

return [NSString stringWithFormat:@"%@' %@\"", @(feet), @(inches)];

That will easily solve the 12 inch problem because the round is applied to the total length in inches.

Upvotes: 10

Related Questions