Search code examples
iosformattingfloating-point-precisionxctest

iOS - remove trailing zeros from float WITHOUT converting to String?


I would like to remove trailing zeros from a float. I found multiple posts, but all answers suggest converting a float to NSString and using NSFormatter.

While this might be good in most cases, I am performing XCTests and I need the values in float - converting generated String back to float does not give correct results.

For input:

arg0 = 0.0001;
arg1 = 0.0011;

I would like a result of 0.0012, but the addition arg0 + arg1 gives the answer of 0.01200 which in turn generates a failing test for XCTest Case.

My method for adding numbers is the simpliest possible:

-(float)addNumber:(float)first toNumber:(float)second {

    return first + second;
}

And the test case as well:

- (void)testAddition3 {

    arg0 = 0.0001;
    arg1 = 0.0011;

    result = [vc addNumber:arg0 toNumber:arg1];

    XCTAssertEqual(result, 0.0012, @"Addition incorrect!");
}

Any ideas on how to do this?


Solution

  • The actual problem is that floating point math is not exact - some numbers cannot be precisely represented in binary, and due to tiny rounding errors and the such, you can't be certain of the result. For a (contrived) example, 1.0 + 1.0 = 1.99999.. This makes things like equality difficult.

    The typical way you compare two floating point numbers is comparing within some error (typically called epsilon). The function you want is XCTAssertEqualWithAccuracy, which will compare two floats with a given precision