NSString stringWithFormat问题

发布于 2024-10-01 11:35:14 字数 285 浏览 1 评论 0原文

我有这样的问题: 双计算值;

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

buf =“7.142857”;

而不是

buf = "7.1428571428571423";

我尝试以这种方式格式化它:@“%f”。 但是当我尝试 @"%14.9f" 时,逗号后显示 9 个符号。

有什么问题吗?我该如何解决它?谢谢!

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.9f" 9 signs after comma displayed.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月流歌 2024-10-08 11:35:14

除非我误解了,否则正确的格式是 @"%.14f"

你所做的,@"%14f" 表示你想要最多 14 位数字,在小数,但您没有指定后面的数字。

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.

甜`诱少女 2024-10-08 11:35:14

我不知道为什么,但 stringWithFormat: 似乎没有正确格式化双精度数。您可以尝试以下方法:

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

它将 buf 设置为 @"7.142857142857142"

为了更严格地控​​制位数,您可以使用 NSNumberFormatter

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文