Probably really simple but I don't understand...
I have an NSString 50.81114
and I want to convert it into a double...
Currently I am using [string doubleValue]
but this is coming out as 50.811140000002
What's going on?!
Disco
due to limited precision double
can't store 50.81114
. The closest value that can be stored in a double is 50.811140000002
.
Use NSDecimalNumber instead. Like this:
NSString *string = @"50.81114";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:string];
Double
(and any floating point number) has its own limit of accuracy, normally it would be around 15-16 digits. Note this is not just for Objective-C, but for all the languages because of the limit of binary floating point presentation.
What you show is just normal, since 50.81114
cannot be accurately presented in binary, approximation must be used.
You can read Wikipedia for further reading.
If you need to maintain this number as a decimal, rather than binary, number then use NSDecimalNumber
rather than double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With