问题描述
我发现%g只在需要时显示小数。如果数字是整数,则不添加尾随.000,这样就好了。
但是在例如1.12345的情况下,我希望它将答案缩短到1.123。
在1.000的情况下我想只显示1,因为%g已经存在。
I've found %g to show only decimals if needed. If the number is whole, no trailing .000 is added, so thats good.But in the case of for example 1.12345 I want it to short the answer to 1.123.And in the case of 1.000 I want to only show 1, as %g already does.
我试图在字符串中指定%。3g ,但这不起作用。
如果有人有答案,我将不胜感激!
I've tried to specify %.3g in the string, but that doesn't work.If anyone has the answer, I'd be grateful!
推荐答案
我查看了格式字符串的功能通过,据我所知,你希望的行为不是可能。
I reviewed the abilities of a "format string" via the IEEE Specification and as I understand it your wished behavior is not possible.
我建议您使用NSNumberFormatter类。我写了一个符合你希望的行为的例子。我希望有所帮助:
I recommend to you, to use the NSNumberFormatter class. I wrote an example that matches your wished behavior. I hope that helps:
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setGroupingSeparator:@""];
NSString *example1 = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:123456.1234]];
NSLog(@"%@", example1);
NSString *example2 = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:123456.00]];
NSLog(@"%@", example2);
这篇关于如果需要,正确使用格式说明符最多可显示三位小数,否则为零小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!