Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString to Double Issue

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

like image 558
StuStirling Avatar asked Aug 03 '11 13:08

StuStirling


3 Answers

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];
like image 98
Matthias Bauch Avatar answered Nov 03 '22 08:11

Matthias Bauch


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.

like image 22
zw324 Avatar answered Nov 03 '22 07:11

zw324


If you need to maintain this number as a decimal, rather than binary, number then use NSDecimalNumber rather than double.

like image 26
Rob Napier Avatar answered Nov 03 '22 08:11

Rob Napier