NSString stringWithFormat 添加百分比

发布于 2024-10-10 00:15:04 字数 246 浏览 0 评论 0原文

如何向 stringWithFormat 函数添加百分比?例如,我想要以下内容:

float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%",someFloat];

这应该导致字符串为:

40.23%

但事实并非如此。我怎样才能实现这个目标?

How can I add a percent to my stringWithFormat function? For example, I'd like to have the following:

float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%",someFloat];

This should cause the string to be:

40.23%

But it is not the case. How can I achieve this?

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

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

发布评论

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

评论(2

北城半夏 2024-10-17 00:15:04

% 是 printf 样式格式的字符开头,只需将其加倍即可:

float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];

% being the character beginning printf-style formats, it simply needs to be doubled:

float someFloat = 40.233f;
NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];
孤檠 2024-10-17 00:15:04

百分号的转义代码是“%%”,因此您的代码将如下所示 这

[NSString stringWithFormat:@"%d%%", someDigit];

对于 NSLog() 和 printf() 格式也是如此。

引用自如何向 NSString 添加百分号

The escape code for a percent sign is “%%”, so your code would look like this

[NSString stringWithFormat:@"%d%%", someDigit];

This is also true for NSLog() and printf() formats.

Cited from How to add percent sign to NSString.

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