开发者

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜