Reputation: 26886
In my test, when I use NSString
's stringWithFormat:@"%.2f"
method to keep two decimal place.
[NSString stringWithFormat:@"%.2f", 9999.999];
result is:
10000.00
[NSString stringWithFormat:@"%.2f", 9999.99];
result is: 9999.99
[NSString stringWithFormat:@"%.2f", 9999.9912];
result is: 9999.99
My requirement is no matter the float
is whatever, I just want to keep two decimal place, such 9999.999
-> 9999.99
, not the result we saw the first example, how to do with this?
Upvotes: 0
Views: 74
Reputation: 11127
Try this code
1) In 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) In 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!)")
Upvotes: 2