Dynamically format a float in a NSString

2020-06-25 04:52发布

Consider this:

NSString *whatever=[NSString stringWithFormat:@"My float: %.2f",aFloat];

This will round my aFloat to 2 decimal places when building the string whatever

Suppose I want the 2 in this statement to be assignable, such that, based on the value of aFloat I might have it show 2 or 4 decimal places. How can I build this into stringWithFormat?

I want to be able to do this without an if that simply repeats the entire line for different cases, but rather somehow dynamically change just the %.2f portion.

3条回答
我命由我不由天
2楼-- · 2020-06-25 05:05

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.

查看更多
We Are One
3楼-- · 2020-06-25 05:12

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];
查看更多
【Aperson】
4楼-- · 2020-06-25 05:14

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];
查看更多
登录 后发表回答