0

I have a piece of code as:

let gate = 0.0 // 1.4 1.3 1.2
let xGate = NSNumber(value: gate)
let xValue = Double(round(xGate.floatValue*100)/100)

switch xValue {
case _ where xValue > gate: print("large")
case _ where xValue < gate: print("little")
default: print("gate")
}

I want to make a float value as my Gate, and it works when I set gate such as 0.0 1.0 2.0, but it fails as 1.1, 1.2 etc.

My question is: is it really safe for 0,0 1.0, 1.5, 2.0 3.0, although these number pass the test?

BollMose
  • 3,002
  • 4
  • 32
  • 41
  • Essentially a duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – A binary floating point number *cannot* represent the value `1.1` exactly. – Martin R Nov 26 '16 at 16:08
  • See also [How should I do floating point comparison?](http://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison) – Martin R Nov 26 '16 at 16:13
  • My question is: is it really safe for 0,0 1.0, 1.5, 2.0 3.0, although these number pass the test? – BollMose Nov 26 '16 at 16:24
  • What's the point of doing the whole `*100/100` bit if the values you start with only have one decimal place to begin with? – rmaddy Nov 26 '16 at 16:30
  • @rmddy I only want to keep 2 decimal. – BollMose Nov 26 '16 at 16:33

0 Answers0