Double-String conversion imprecision

Hi,

I'm looking to get some ideas from the community about a particular issue that I often face and would love to settle on an answer to. An example of the more general issue I'm referring to is when a unit test fails because 12.000000001 is not equal to 12.0. These tiny discrepancies seem to often get introduced when working with Double. I believe that converting to and from String/Data is a common cause.

One of the possible holistic answers to this issue that I'm toying with is the possibility that actually comparing two doubles for exact equality is generally ill-advised. Maybe the issue is that exact equality is a more relevant question to ask for discrete values, whereas continuous values shine in contexts where greater-than/less-than comparison is what's needed.

I was just in the middle of writing a unit test which failed for this reason and that was sufficient motivation for me to write to the community to ask for advice. What do you think?

You could use the overload of XCTAssertEqual which accepts an accuracy argument to apply a tolerance.

1 Like

You can write a comparison method that reports that they're equal if the difference between the two values is less than a certain threshold.

Terms of Service

Privacy Policy

Cookie Policy