I want to send an NSNumber created with a float with only two fraction digits.
So I'm creating a NSNumberFormatter with 2 Fraction Digits, but it doesn't respect the number of Fraction Digits.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.maximumFractionDigits = 2;
formatter.roundingMode = NSNumberFormatterRoundUp;
NSString *preformatedPreAuthPrice = [formatter stringFromNumber:@(4.44)];
self.PreAuthPrice=[formatter numberFromString:preformatedPreAuthPrice];
when I print the type of NSNumber, it's a double
p strcmp([(NSNumber *)[dictionary objectForKey:@"PreAuthPrice"] objCType], @encode(double))
(int) $1 = 0
And if I get the value:
po [self.PreAuthPrice doubleValue]
4.4400000000000004
Even if I do:
po [@(4.44) doubleValue]
4.4400000000000004
The interesting thing is, when I send this NSNumber (Using AFNetworking version 2.6,3 and 3.1.0 ) with iOS 10, it sends the right value, 4.44. But with iOS 11 it sends 4.4400000000000004
This is captured with Charles:
iOS 10
{
"preAuthPrice": 4.44,
}
iOS 11
{
"preAuthPrice": 4.4400000000000004
}
Also I found this in the release notes for the foundation library:
NSNumber
Bridging NSNumbers in swift to numeric types now uniformly limits the cases of as? cast no matter how the NSNumber was created. Casting NSNumbers to numeric types will return nil if the number cannot be safely represented as the target type.
Is this happening to anyone? Could it be related with the release notes? It’s in iOS 10 sending [self.PreAuthPrice stringValue] and in iOS 11 [self.PreAuthPrice doubleValue]
I know a solution it’s to send the value as a String, and also I after reading:
Why Are Floating Point Numbers Inaccurate?
And
Why can't decimal numbers be represented exactly in binary?
I know that it could be the problem, but then why is working with iOS 10.