How to store exact digits in Firestore

Viewed 230

How do I store exact values for numbers in Firestore from the Objective-C SDK?

For instance, if I manually create an "abv" field with a value of "15.9", it shows that exact value.

enter image description here

However, if I update a value in Firestore from the Objective-C API with an NSNumber value of @(15.9), I get this approximate value in my Firestore document.

enter image description here

NSDictionary *data = @{@"abv": @(15.9)};
[documentReference updateData:data completion:^(NSError * _Nullable error) {

}];

Here's another example. I attempted to store the value 61.99 from my Objective-C app. I can manually edit the amount back to 61.99 from the web console. I do not understand why I can manually input exact decimal values from the web console but not from the Objective-C API.

enter image description here enter image description here

2 Answers

This is a known issue with numerical accuracy of floats and well documented. You could handle the number before writing it into firestore i.e. keep the input as a string write it into firestore and handle the number afterwards. This Blog goes into some detail about it and I think will handle your case better or as @skaak says keep as a string write the value into firestore and handle using the method depicted in the blog.

This solved the issue by using NSDecimalNumber. I can store numbers exactly now with two decimal precision.

NSNumber *number = (NSNumber *)value;
NSString *text = [NSString stringWithFormat:@"%.2f", number.doubleValue];
NSDecimalNumber *decimalNumber = [[NSDecimalNumber alloc] initWithString:text];
return decimalNumber;
Related