For the expression 59.99 + 0.01, the expected result is 60.0, but I'm getting 60.0999.... I understand that this discrepancy is due to floating-point computing. How can I avoid this issue?
I'm also writing a test case, and in most situations, the result is not 60.0. MathSolver is a simple wrapper for try str.evaluate().
func testExample() throws {
// 59.99 + 0.01 -> ("60.099999999999994") is not equal to ("60.0")
for n in 1...99 {
let lhs = "59." + Array(repeating: "9", count: n).joined()
let rhs = "0." + Array(repeating: "1", count: n).joined()
let result = MathSolver.solve(lhs + " + " + rhs)!
XCTAssertEqual(result, 60.0, "\n🔢 \(lhs)")
}
}
For the expression
59.99 + 0.01
, the expected result is60.0
, but I'm getting60.0999....
I understand that this discrepancy is due to floating-point computing. How can I avoid this issue?I'm also writing a test case, and in most situations, the result is not 60.0.
MathSolver
is a simple wrapper fortry str.evaluate()
.