当我转换时NSNumber
使用“floatValue”来浮点值,精度上存在差异。例如,我有一个NSNumber
'myNumber' 的值为 2.3,如果我使用 'floatValue' 将 myNumber 转换为浮点数,则其值变为 2.29999。但我正好需要 2.30000。 2.3之后的零个数没有问题,我需要'2.3'而不是'2.9'。
我怎样才能这样做呢?
我遇到了类似的情况,我正在读取值并将其再次分配回浮点变量。
我的问题陈述:
NSString *value = @"553637.90";
NSNumber *num = @([value floatValue]); // 1. This is the problem. num is set to 553637.875000
NSNumberFormatter *decimalStyleFormatter = [[NSNumberFormatter alloc] init];
[decimalStyleFormatter setMaximumFractionDigits:2];
NSString *resultString = [decimalStyleFormatter stringFromNumber:num]; // 2. string is assigned with rounded value like 553637.88
float originalValue = [resultString floatValue]; // 3. Hence, originalValue turns out to be 553637.88 which wrong.
更改线路后,以下内容对我有用:
NSNumber *num = @([value doubleValue]); // 4. doubleValue preserves value 553637.9
double originalvalue = [resultString doubleValue]; // 5. While reading back, assign to variable of type double, in this case 'originalValue'
我希望这会有所帮助。 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)