开发者

How to format a number such a way that there is always one fractional digit?

For example, I have float values like:

0.2 1.5 2.0 3.0 10.0 52.5 60.0

Under any circumstances, I really want one fractional digit. Even if the number is exactly 1, i want it to be displayed as 1.0

I tried to set up an NSNumberFormatter like this, but it doesn't work:

NSNumberFormatter *formatter = [[NSNumber开发者_如何学GoFormatter alloc] init];
[formatter setAlwaysShowsDecimalSeparator:NO];
[formatter setAllowsFloats:YES];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setMinimumFractionDigits:1];

[formatter setUsesSignificantDigits:YES];
[formatter setMinimumSignificantDigits:2];

[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];

It shows 0.2, 5.0, 5.5, 9.0,

but when it reaches 10, it would show 10, 10.3, 11, 11.9, 15, ... and so on. Is this something NSNumberFormatter can't do?


setAlwaysShowsDecimalSeparator: Controls whether the receiver always shows the decimal separator, even for integer numbers.

Try setting this to YES


try this?

NSString * f= [NSString stringWithFormat:@"%.01f",(float)10];


I could not use madmi3 solution's because I need to set the locale of the NSNumberFormatter dynamically.

So ended up using the following solution:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.alwaysShowsDecimalSeparator = YES; // This will produce results like 10. for intergers
formatter.maximumFractionDigits = 1;
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"pt"]; // I get this locale dinamically

NSString *formattedNumber = [formatter stringFromNumber:[NSNumber numberWithInteger:10]];

//Check this formattedNumber is ending with the separator
//If so, then append one more 0.
if ([formattedNumber hasSuffix:[formatter.locale objectForKey:NSLocaleDecimalSeparator]])
{
    formattedNumber = [formattedNumber stringByAppendingString:@"0"];
}

NSLog(@"%@", formattedNumber);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜