Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: how to compare the first n digits past the decimal place for CGFloat?

How can you compare if A and B, both CGFloats, are equal up to 5 digits past the decimal place? This is necessary because of this issue.

like image 724
Crashalot Avatar asked May 06 '15 22:05

Crashalot


People also ask

How do I get only 2 decimal places in Swift?

The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.

How do you compare floating point numbers?

Relative Comparison of Floating-point ValuesIf a and b differ in sign then returns the largest representable value for T. If both a and b are both infinities (of the same sign), then returns zero. If just one of a and b is an infinity, then returns the largest representable value for T.

How do you round a Float value in Swift?

Swift provide a built-in function named as floor() function. This function is used to round the given number to the nearest largest integer value which is less than or equal to the given number. It accept also both Float and Double.

How do I set precision in Swift?

If you'd like to interpolate a float or a double with a String in Swift, use the %f String format specifier with appropriate number in order to specify floating point precision. Note that Swift automatically rounds the value for you.


1 Answers

The same as you would compare floating point numbers in any other language.

Take the absolute value of the difference of the numbers and compare it against your acceptable delta.

let delta: CGFloat = 0.00001

let a: CGFloat = 3.141592
let b: CGFloat = 3.141593


if abs(a-b) < delta {
    println("close enough for government work")
}
like image 61
nhgrif Avatar answered Sep 22 '22 18:09

nhgrif