开发者

NSString stringWithFormat problem

开发者 https://www.devze.com 2023-01-23 19:32 出处:网络
I have such a problem: double calcValue; NSString *buf = [NSString stringWithFormat:@\"%14f\", myCalculator.calcValue];

I have such a problem: double calcValue;

NSString *buf = [NSString stringWithFormat:@"%14f", myCalculator.calcValue];

buf = "7.142857";

istead of

buf = "7.1428571428571423";

I tried to format it in such ways: @"%f". But when I tried @"%14.9开发者_如何转开发f" 9 signs after comma displayed.

Whats the problem? And how can I solve it? Thanx!


Unless I'm misunderstanding, the correct format would be @"%.14f.

What you did, @"%14f" says you want up to 14 digits, before the decimal, but you didn't specify digits after.


I'm not sure why, but stringWithFormat: doesn't seem to format doubles properly. You might try this approach:

double calcValue=7.1428571428571423;
NSString *buf=[[NSNumber numberWithDouble:calcValue] stringValue];

which will set buf to @"7.142857142857142".

For tighter control over number of digits, you could use a NSNumberFormatter.

0

精彩评论

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