StuStirling
StuStirling

Reputation: 16191

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

Upvotes: 6

Views: 2415

Answers (3)

Rob Napier
Rob Napier

Reputation: 299355

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

Upvotes: 1

Matthias Bauch
Matthias Bauch

Reputation: 90117

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];

Upvotes: 11

zw324
zw324

Reputation: 27190

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.

Upvotes: 2

Related Questions