I have this Info.
let params2: [String: AnyObject] = [
"app_token": myapptoken,
"member_access_token": accessToken!,
"pay_process": 0,
"payamount_credit": 9.87 //hardcode
]
When print params2
The result is
["app_token": myapptoken, "member_access_token": accessToken, "payamount_credit": 9.869999999999999, "pay_process": 0]
The "payamount_credit": 9.87
now is "payamount_credit": 9.869999999999999
I have tried all the ways that exist round but behaves the same.
NSString(format: "%.\2f", 9.87)
Double(round(1000*9.87)/1000)
The strangest thing of all is that only happens with this specific number (9.87), is something mystical.
Playground Screen.
The problem lies within the numeric precission, simply put, some numbers cannot be defined as a
Double
without losing precision.Instead you should use NSDecimalNumber:
Try using this function:
I think the best thing to do here is to explicitly use a float instead of a double because the precision of a double is not necessary if you only want two decimal places. This function just helps round it a bit more accurately.
Don't use floats or doubles to represent currency, for precisely (pun) this reason. Use NSDecimalNumber instead (see Which Swift datatype do I use for currency).
NSDecimalNumber takes some effort to use, but it does perform base 10 arithmetic. To use it correctly, you have to read up a bit on the API. In particular, to do rounding you need to supply an NSDecimalNumberHandler (you can set a default one to use).
Good stuff to read:
I think that the Playground shows an unexpected result because it is coercing the internal value of the NSDecimalNumber to a Double before displaying it (I would welcome alternative or authoritative explanations, because I do find this curious). However the internal representation should be correct.
Try out this in your Playground:
Don't assume that Float is a more accurate representation of the number, it just happens to work better here. If you keep your calculations (like taxes, discount, shipping, etc.) in the NSDecimalNumber realm, they will be accurate.
Swift 3 / Xcode beta 1 bonus:
Playground behavior is still the same, but changes the Great API Renaming Rodeo changes the above code to:
The change here is that the global NSRoundingMode enum goes away, and is replaced by the enum RoundingMode which is a member of NSDecimalNumber.