0

We are using Parse-iOS SDK in our project written in Objective-C.

When I try to save the NSNumber 0.01 on an object, it saves as 0.00999999776482582. Saving any number—including whole numbers—results in a strange decimal representation of it being saved.

This happens from this code:

PFObject *object = [PFObject objectWithoutDataWithClassName:@"Thing" objectId:ID];
object[@"decimalNumber"] = decimalNumber;
[object saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
    });

This issue just started and we haven't had it before.

Our problem is caused by the same issue as you can see here: https://github.com/parse-community/Parse-SDK-iOS-OSX/issues/966

This might be related to but is not the same as the following post. We are looking for a solution along with an explanation, not just an explanation. Is floating point math broken?

How can we solve this problem?

mdimarca
  • 163
  • 11
  • Yes, this really is a dupe. In C and C derived languages-- in most languages, actually-- decimal numbers are weird like this. The solution is either to round the numbers for display purposes or to store the numbers using some other means, likely an "infinite" precision math library. – bbum Oct 25 '18 at 22:25
  • The duplicate doesn't have an answer so it's pointless to mark it as such. For anyone who encounters this in the future, here's the solution: At first, I converted the NSString to a float and then to an NSNumber. While it printed properly in my app, it saved improperly as this issue is about. The solution is to use the following code to avoid the problem altogether: NSNumberFormatter *f = [[NSNumberFormatter alloc] init]; f.numberStyle = NSNumberFormatterDecimalStyle; NSNumber *price = [f numberFromString:priceStringWithoutCurrencyCharacter]; – mdimarca Oct 25 '18 at 22:39
  • 2
    @mdimarca - your solution could still be using binary floating point, and as such is subject the the same issues when representing decimal fractions. Take a local at [`NSDecimalNumber`](https://developer.apple.com/documentation/foundation/nsdecimalnumber?language=objc) for how to use decimal floating point. – CRD Oct 25 '18 at 23:32
  • Converting through a string will be, at best, slow and will quite likely lose precision along the way. As CRD said, NSDecimalNumber will likely solve needs to the precision required, but maybe not. We don't have enough information to know. – bbum Oct 25 '18 at 23:47

0 Answers0