davedelong / DDMathParser

String → Number
MIT License
854 stars 153 forks source link

A simple question about 59.99 + 0.01 #184

Closed rijieli closed 1 year ago

rijieli commented 1 year ago

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)")
    }
}
rijieli commented 1 year ago

Duplicate to #99