iphone - 数字格式

标签 iphone objective-c ios

大家好,我正在使用下面的方法从 NSNumber 获取字符串

     -(NSString *)stringFromNumber:(NSNumber *)number
    {
        NSLog(@"Input:---%@",number);
        NSNumberFormatter *numFormatter = [[[NSNumberFormatter alloc] init] autorelease];
        [numFormatter setMaximumFractionDigits:5];
        [numFormatter setMinimumFractionDigits:2];
        //[numFormatter setExponentSymbol:@"e"];
        NSString *str_num = [numFormatter stringFromNumber:number];
        NSLog(@"Output:---%@",str_num);
        return str_num;
    }

在控制台中我的情况如下

    Input:---2.940000057220459
    Output:---2.94                
    Input:---2940.000057220459
    Output:---2940.00006         
    Input:---2.940000057220459e-15
    Output:---.00                 
    Input:---2.940000057220459e-12
    Output:---.00                 
    Input:---2.940000057220459e-09
    Output:---.00                 
    Input:---2.940000057220459e-06
    Output:---.00                 
    Input:---0.002940000057220459
    Output:---.00294             

但对于上述输入(顺序),我需要输出如下所示

---2.94
---2940
---2.94e-15
---2.94e-12
---2.94e-6
---2.94e-9
---0.00294

我该怎么做?请有人帮助我。

最佳答案

我试过了

-(NSString *)stringFromNumber:(NSNumber *)number
{
    NSLog(@"Input:---%@",number);
    NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
    [numFormatter setMaximumFractionDigits:5];
    [numFormatter setMinimumFractionDigits:2];
    NSString *temp = [NSString stringWithFormat:@"%@",number];
    NSRange range = [temp rangeOfString:@"e"];
    if(range.length > 0){
        [numFormatter setNumberStyle:NSNumberFormatterScientificStyle];
        [numFormatter setExponentSymbol:@"e"];
    }
    NSString *str_num = [numFormatter stringFromNumber:number];
    NSLog(@"Output:---%@",str_num);
    return str_num;
}

就这样了

Input:---2.940000057220459
Output:---2.94
Input:---2940.000057220459
Output:---2940.00006
Input:---2.940000057220459e-15
Output:---2.94e-15
Input:---2.940000057220459e-12
Output:---2.94e-12
Input:---2.940000057220459e-09
Output:---2.94e-9
Input:---2.940000057220459e-06
Output:---2.94e-6
Input:---0.002940000057220459
Output:---.00294

关于iphone - 数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10279031/

相关文章:

iphone - 推送通知代理未被调用

android - 移动网站的图像尺寸是多少才能容纳 100% 的可用屏幕?

objective-c - 对于 iOS 6,如何在后台线程上加载数据然后更新 UI?

objective-c - TableView 交互阻止单元格中的动画

ios - 如何在UIPageViewController最后一页向右滑动时弹出消息?

ios - 仅从 UIView 的 3 个边绘制阴影

iphone - 使用 native Trigger.IO API 将 UIImage 传递给 JS

ios - iOS 推送通知的位置请求(当应用程序未在后台运行时)

ios - 查找从哪个地区的应用商店下载 iOS 应用

ios - NSLinguisticTagger enumerateTagsInRange 在具有 NSLinguisticTagSchemeNameTypeOrLexicalClass 的设备上不起作用