0

I have func in my app which trims numbers, e.x. 9.81->9.8. But after updating swift behavior has changed.

let myNum = 9.7
print(round(myNum / 0.1) * 0.1)

Swift 4.1.2 output - 9.7 
Swift 4.2 output - 9.700000000000001

Please advise how to resolve this issue. May it is swift's bug?

Paul
  • 343
  • 1
  • 17

2 Answers2

3

If you need the correct value itself, and not just a String representation, you can try this.

let value = 9.71
let roundedValue = round(value * 10) / 10
print(roundedValue)

It prints 9.7 on Swift 4.2, so I guess that the rounded value is correct and you can use it for additional computations.

Yury Imashev
  • 2,068
  • 1
  • 18
  • 32
1

This seems to be what you want:

let trimmedString = String(format: "%@.1f", round(myNum / 0.1) * 0.1)
meaning-matters
  • 21,929
  • 10
  • 82
  • 142