NSString for dual release

Probably very simple, but I do not understand ... I have an NSString 50.81114 and I want to convert it to double ...
I am currently using [string doubleValue] , but it comes out as 50.811140000002
What's happening?!

Disco

+6
source share
3 answers

Double (and any floating point number) has its own precision limit, usually it will be about 15-16 digits. Please note that this is not only for Objective-C, but for all languages โ€‹โ€‹because of the limit of representing binary floating point.

What you are showing is just normal, since 50.81114 cannot be accurately represented in binary format, you need to use approximation.

You can read Wikipedia for further reading.

+2
source

due to limited accuracy, double cannot store 50.81114 . The closest value that can be stored in double is 50.811140000002 .

Use NSDecimalNumber . Like this:

 NSString *string = @"50.81114"; NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:string]; 
+11
source

If you need to store this number as a decimal, not a binary number, use NSDecimalNumber , not double .

+1
source

Source: https://habr.com/ru/post/894193/


All Articles