如何格式化数字以使其始终有一个小数位?
例如,我的浮点值如下:
0.2 1.5 2.0 3.0 10.0 52.5 60.0
无论如何,我真的想要一位小数。即使数字正好是 1,我希望它显示为 1.0
我尝试像这样设置 NSNumberFormatter,但它不起作用:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setAlwaysShowsDecimalSeparator:NO];
[formatter setAllowsFloats:YES];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setMinimumFractionDigits:1];
[formatter setUsesSignificantDigits:YES];
[formatter setMinimumSignificantDigits:2];
[formatter setNumberStyle:kCFNumberFormatterDecimalStyle];
它显示 0.2、5.0、5.5、9.0,
但是当它达到 10 时,它将显示 10, 10.3, 11, 11.9, 15, ... 等等。 这是 NSNumberFormatter 无法做到的吗?
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 = [[NSNumberFormatter 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将其设置为 YES
Try setting this to YES
试试这个?
NSString * f= [NSString stringWithFormat:@"%.01f",(float)10];
try this?
NSString * f= [NSString stringWithFormat:@"%.01f",(float)10];
我无法使用 madmi3 解决方案,因为我需要动态设置 NSNumberFormatter 的区域设置。
所以最终使用了以下解决方案:
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: