NSNumber stringValue different from NSNumber value

后端 未结 1 1819
被撕碎了的回忆
被撕碎了的回忆 2021-02-11 05:42

I\'m having problems with converting NSNumber to string and string to NSNumber.

Here\'s a sample problem:

NSString *stringValue         


        
1条回答
  •  -上瘾入骨i
    2021-02-11 06:20

    You are discovering that floating point numbers can't always be represented exactly. There are numerous posts about such issues.

    If you need to get back to the original string, then keep the original string as your data and only convert to a number when you need to perform a calculation.

    You may want to look into NSDecimalNumber. This may better fit your needs.

    NSString *numStr = @"9.2";
    NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithString:numStr];
    NSString *newStr = [decNum stringValue];
    NSLog(@"decNum = %@, newStr = %@", decNum, newStr);
    

    This gives 9.2 for both values.

    0 讨论(0)
提交回复
热议问题