Objective-C:如果小数点后有一些值,如何将小数加倍到2位小数,否则该值应舍入为0小数位

时间:2016-02-01 11:26:32

标签: objective-c

如何格式化decial值,如下所示:

/// variable
double value = 9.99999

/// conversion
NSSting* str = [NSString stringWithFormat:@"%.2f", value];

/// result
9.99

但当值 9.00000 时,它返回 9.00

如何格式化显示9.0000 as 99.99999 as 9.99 ??

的字符串

2 个答案:

答案 0 :(得分:3)

你应该看看NSNumberFormatter。 我在Swift中添加了代码,但您可以轻松地将其转换为Objective-C:

let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
formatter.roundingMode = NSNumberFormatterRoundingMode.RoundFloor
print("\(formatter.stringFromNumber(9.00))")

// Objective-C(Credit to NSNoob)

        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        [formatter setNumberStyle: NSNumberFormatterDecimalStyle];
        formatter.minimumFractionDigits = 0;
        formatter.maximumFractionDigits = 2;
        [formatter setRoundingMode:NSNumberFormatterRoundFloor];
        NSString* formattedStr = [formatter stringFromNumber:[NSNumber numberWithFloat:9.00]];
        NSLog(@"number: %@",formattedStr);

答案 1 :(得分:1)

According to this related question's answer,您可以尝试:

// Usage for Output   1 — 1.23
[NSString stringWithFormat:@"%@ — %@", [self stringWithFloat:1], 
                                       [self stringWithFloat:1.234];

// Checks if it's an int and if not displays 2 decimals.
+ (NSString*)stringWithFloat:(CGFloat)_float
{
    NSString *format = (NSInteger)_float == _float ? @"%.0f" : @"%.2f";
    return [NSString stringWithFormat:format, _float];
}

在Swift中,您可以使用" %g" ("使用最短的表示")格式说明符:

import UIKit

let firstFloat : Float = 1.0
let secondFloat : Float = 1.2345

var outputString = NSString(format: "first: %0.2g second: %0.2g", firstFloat, secondFloat)

print("\(outputString)")

回来了:

"first: 1 second: 1.2"