Dynamically format a float in a NSString

余生长醉 提交于 2019-12-03 20:24:50

You will need to build the format first:

NSInteger precision = 2;
NSString *format = [@"My float: %." stringByAppendingFormat:@"%d", precision];
format = [format stringByAppendingString:@"f"];

NSString *whatever=[NSString stringWithFormat:format, aFloat];

The proper answer is to use an NSNumberFormatter.

However, the easy answer that uses format strings is to use the asterisk specifier. According to the Apple documentation the format string conforms to the IEEE printf specification. This specification states the following:

A field width, or precision, or both, may be indicated by an asterisk ( '*' ). In this case an argument of type int supplies the field width or precision.

This means that

int precision = 2;
NSString *whatever=[NSString stringWithFormat:@"My float: %.*f", precision,aFloat];
//                                   Asterisk in place of 2^^    ^^^^^^^^^ int variable

should work. I have to say, I haven't tried it though, I tend to use NSNumberFormatters.

Escape % as %% to build format strings:

NSUInteger digits = aFloat > 10.0f ? 2 : 4;
NSString *format = [NSString stringWithFormat:@"My float: %%.%if", digits];
NSString *whatever = [NSString stringWithFormat:format, aFloat];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!