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.
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.
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.
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.
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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With