Correcting floating point numbers

后端 未结 2 1351
予麋鹿
予麋鹿 2020-12-01 22:12

I am wondering if there is a way that you can easily and safely correct floating point numbers.

For example,

When entered: \" 32 + 32.1 \" Result: \"64.09999

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 22:58

    You can't "correct" a floating point number because floating point numbers simply cannot represent the number you want.

    Floating point numbers are remarkably imprecise and, generally, shouldn't be used for anything that involves lots of calculations because the cumulative error is often catastrophically bad.

    Use a double instead. They can represent a much greater range of values and, as a result, can represent many more values quite precisely. If that isn't good enough, you'll need to move to something with more precision. Possibly NSDecimalNumber.

提交回复
热议问题