[英]NSNumber stringValue different from NSNumber value
I'm having problems with converting NSNumber
to string and string to NSNumber
. 我在与转换问题
NSNumber
串和字符串NSNumber
。
Here's a sample problem: 这是一个示例问题:
NSString *stringValue = @"9.2";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSLog(@"stringvalue:%@",[[formatter numberFromString: stringValue] stringValue]);
Output will be: 输出将是:
stringvalue:9.199999999999999
I need to retrieve the original value, where, in the example should be 9.2
. 我需要检索原始值,在示例中,其中应为
9.2
。 On the contrary, when the original string is 9.4
the output is still 9.4
. 相反,当原始字符串为
9.4
,输出仍为9.4
。 Do you have any idea how to retrieve the original string value without NSNumber
doing anything about it? 您是否知道如何在不使用
NSNumber
进行任何操作的情况下检索原始字符串值?
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
. 您可能需要研究
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. 这两个值均为
9.2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.