Ancinek - 7 months ago 31

Swift Question

I am trying to round a number in swift, and I found a solution using this:

`func roundTo(number: Double, precision: Int) -> Double {`

var power: Double = 1

for _ in 1...precision {

power *= 10

}

let rounded = Double(round(power * number)/power)

return rounded

}

I have a model class, lets call it MyObject.

`class: My Object {`

var preciseNumber: Double?

}

I am fetching a number for example:

`var myNumber = 10,0123456789`

I use my roundTo function to round it so I have 10,0123456 (7 numbers after the decimal point).

When I print a statement:

`print("myNumber rounded: \(roundTo(myNumber, precision: 7))") //10,0123456 as a result. Great!`

Then next I want to assing rounded myNumber to my class variable preciseNumber so:

`let roundedNumber = roundTo(myNumber, precise: 7)`

print("Rounded number is: \(roundedNumber)") // 10,01234567 as result

self.preciseNumber = roundedNumber

print("Precise number is now: \(self.preciseNumber)") // 10,01234599999997 as result

What might be causing this? I want to be as precise as possible.

Answer

So it sounds like your issue is being able to compare floating point numbers. The best way to do this is to instead find the degree of precision you need. So rather than just checking `numOne == numTwo`

use something like `abs(one - two) <= 0.000001`

You can create a Swift operator to handle this for you pretty easily:

```
// `===` is just used as an example
func === (one: Double, two: Double) -> Bool {
return abs(one - two) <= 0.000001
}
```

Then you can just check `numOne === numTwo`

and it will use a better floating point equality check.