Merging different Swift 4 answers together:
import Foundation
infix operator ~==
infix operator ~<=
infix operator ~>=
extension Double {
static func ~== (lhs: Double, rhs: Double) -> Bool {
// If we add even a single zero more,
// our Decimal test would fail.
fabs(lhs - rhs) < 0.000000000001
}
static func ~<= (lhs: Double, rhs: Double) -> Bool {
(lhs < rhs) || (lhs ~== rhs)
}
static func ~>= (lhs: Double, rhs: Double) -> Bool {
(lhs > rhs) || (lhs ~== rhs)
}
}
Usage:
// Check if two double variables are almost equal:
if a ~== b {
print("was nearly equal!")
}
Note that ~<= is the fuzzy-compare version of less-than (<=) operator,
And ~>= is the fuzzy-compare greater-than (>=) operator.
Also, originally was using Double.ulpOfOne, but changed to constant (to be even more fuzzy).
Testing
import Foundation
import XCTest
@testable import MyApp
class MathTest: XCTestCase {
func testFuzzyCompare_isConstantBigEnough() {
// Dummy.
let decimal: Decimal = 3062.36
let double: Double = NSDecimalNumber(decimal: decimal).doubleValue
let doubleCorrect: Double = 3062.36
// Actual test.
XCTAssertEqual(decimal, Decimal(double));
XCTAssertNotEqual(doubleCorrect, double);
XCTAssertTrue(doubleCorrect ~== double);
}
func testDouble_correctConstant() {
XCTAssertEqual(Double.ulpOfOne, 2.220446049250313e-16)
}
}