0
let value:Float = 5.678434
let roundedValue = round(value * 100) / 100

roundedValue Float 5.6784339

how to get 5.67 or 5.68?

  • The result can be different from 5.68 due to the limited precision of binary floating point numbers (see https://stackoverflow.com/questions/588004/is-floating-point-math-broken), but is should be close to 5.68 and not 5.6784339. Are you sure that you print the correct variable? – Martin R Dec 28 '17 at 07:52
  • I am getting 5.68 here too, do not know if you are checking it correctly. Also, maybe check with `roundf` instead of `round`. – Oxthor Dec 28 '17 at 07:53
  • If you want properly rounded to nth decimal position, you should use [`Decimal`](https://developer.apple.com/documentation/foundation/decimal), instead of `Float`. – user28434'mstep Dec 28 '17 at 08:35

1 Answers1

1
extension Float {
    func rounded(toPlaces places:Int) -> Float {
        let divisor = pow(10.0, Float(places))
        return (self * divisor).rounded() / divisor
    }
}

let floatNumber:Float = 3.67565676

print(floatNumber.rounded(toPlaces: 2)) 

//prints 3.68

Sameh Salama
  • 765
  • 1
  • 7
  • 17