iPhone NSNumberFormatter for less than 1 value
I have a floating point value
i.e. 0.0467
Want have a string
05
how can get it? Excluding the decimal point (.).
More precisely, if I have a floating point num开发者_如何学Cber, I want to divide it to integral and decimal, preferably into two string parts.
By following this, you will get desired result.
float floatValue = 0.0467;
NSString *str = [NSString stringWithFormat:@"%.2f", floatValue];
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:@""];
NSLog(@"%@", str); // Result will be: 05
fDecimal = 0.04567;
NSString * strDecimal = [NSString stringWithFormat:@"%0.2f", fDecimal];
NSString * strDecimalPart = [strDecimal substringWithRange:NSMakeRange(2, 2)];
The setting you are looking for is called fraction digits:
NSNumberFormatter* f = [[[NSNumberFormatter alloc] init] autorelease;
[f setMaximumFractionDigits:2];
Optionally you can use -[NSNumberFormatter setRoundingMode:]
to specify how rounding should be done.
精彩评论