如何保持两位小数正确?

时间:2016-12-14 03:15:23

标签: ios objective-c nsstring

在我的测试中,当我使用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,不是我们看到第一个例子的结果,该怎么办?

1 个答案:

答案 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!)")