Reputation: 11740
How to format a decial value as follows:
/// variable
double value = 9.99999
/// conversion
NSSting* str = [NSString stringWithFormat:@"%.2f", value];
/// result
9.99
but when the value is 9.00000 it is returning 9.00
How should I format the string that it would show 9.0000 as 9
and 9.99999 as 9.99
??
Upvotes: 3
Views: 3135
Reputation: 25459
You should have a look on NSNumberFormatter. I added the code in Swift but you can easily convert it to 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 goes 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);
Upvotes: 4
Reputation: 89509
According to this related question's answer, you can try doing:
// 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];
}
In Swift, you can use the "%g
" ("use the shortest representation") format specifier:
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)")
comes back with:
"first: 1 second: 1.2"
Upvotes: 2