0

I found a issue that seems strange, or something I don't understand. The following is a very simple variable assignment:

let f: Float = 310.15

In debugger, I see it is 310.149994 I need to send the value as 310.15 to server, but 310.149994 is received instead.

Is this a Swift compiler or runtime bug? Or any way I can ensure 310.15 float is sent? (I cannot change the server API signature)

Sean
  • 2,967
  • 2
  • 29
  • 39
  • See https://stackoverflow.com/questions/588004/is-floating-point-math-broken?r=SearchResults&s=1|817.0710 – rmaddy Aug 30 '19 at 04:33
  • 3
    Use `Decimal` instead of Float or Double if you need to avoid rounding errors. – Gereon Aug 30 '19 at 05:08
  • When you convert .1 or 1/10 to base 2 (binary) you get a repeating pattern after the decimal point, just like trying to represent 1/3 in base 10. The value is not exact, and therefore you can't do exact math with it using normal floating point methods. original answer in - https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Jeesson_7 Aug 30 '19 at 06:00
  • Thanks for all the comments above answer the question I have. It is @Gereon's suggestion solve my immediate issue, and I finally realize why most of the modem programming language provide Decimal class in additional to those primitive data types. Thanks all. – Sean Aug 30 '19 at 21:15

1 Answers1

-3

Try this one

let f : Float = 310.149954

print(round(1000*f)/1000)

result : 310.15

Nilesh R Patel
  • 697
  • 7
  • 17