ios - NSNumber 到浮点值

标签 ios

当我使用“floatValue”将 NSNumber 转换为浮点值时,精度有所不同。例如,我有一个值为 2.3 的 NSNumber 'myNumber',如果我使用 'floatValue' 将 myNumber 转换为 float ,它的值变为 2.29999。但我正好需要 2.30000。 2.3 之后的零个数没有问题,我需要“2.3”而不是“2.9”。

我该怎么做?

最佳答案

我遇到过类似的情况,我正在读取值并将其重新分配回 float 变量。

我的问题陈述:

 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'

希望对您有所帮助。 :)

关于ios - NSNumber 到浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15087645/

相关文章:

ios - XCode 如何设置 UISlider.setMinimumTrackImage 进行裁剪,而不是缩放

ios - Apple 审核流程的应用程序配置

iphone - NSArray 得到一个 EXC_BAD_ACCESS

ios - Firebase 没有收到键值 Swift

iphone - 缺少 UIView 的 anchorPoint 属性

ios - MPMoviePlayerController 切换视频

ios - 如何为 iPhone 安装 phonegap Facebook 插件

ios - 使 UIImageView(箭头图像)指向我在屏幕上触摸的位置

ios - ProprtyType 的文本字段值与 Reactive Cocoa 4

ios - UIView transitionFromView