1

I am storing some value in Float variable in swift 3. But when I actually use this value from the variable, it loses it precision. I have tried it in playground. It gives me final output as: 152.399994 instead of 152.4 (or 152.40)

Please consider below code:

let feetToInchMultiplier: Float = 12
  let inchToCentimeterMultiplier: Float = 2.54

func heightInCentimeters(_ feet: Float, inches: Float) -> Float {
    //Convert in Centemeters
    let totalInches: Float = (feet * feetToInchMultiplier) + inches
    let centimeters: Float = totalInches * inchToCentimeterMultiplier
    return centimeters
}

heightInCentimeters(5, inches: 0)

If anyone facing this issue please help me out. Thanks in advance.

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38

1 Answers1

0

Float variable always return standard float value with predefine precisions you have to manually change the precisions you want to show. Change your heightInCentimeters method with below and you will get desired out put.

func heightInCentimeters(_ feet: Float, inches: Float) -> Float {
    //Convert in Centemeters
    let totalInches: Float = (feet * feetToInchMultiplier) + inches
    let centimeters: Float = totalInches * inchToCentimeterMultiplier

    return Float(String(format: "%.2f",centimeters))!
}
Nishant Bhindi
  • 2,242
  • 8
  • 21