在我的测试中,当我使用NSString
的{{1}}方法保留两位小数时。
stringWithFormat:@"%.2f"
结果是:
[NSString stringWithFormat:@"%.2f", 9999.999];
10000.00
结果是:[NSString stringWithFormat:@"%.2f", 9999.99];
9999.99
结果是:[NSString stringWithFormat:@"%.2f", 9999.9912];
我的要求是无论9999.99
是什么,我只想保留两位小数,例如float
- > 9999.999
,不是我们看到第一个例子的结果,该怎么办?
答案 0 :(得分:2)
试试此代码
1)在Objective-c
:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:99.9999]];
NSLog(@"numberString - %@",numberString);
2)在swift
:
let formatter:NumberFormatter = NumberFormatter.init()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down
let numberString = formatter.string(from: NSNumber.init(value: 99.9999))
print("numberString - \(numberString!)")