【问题标题】:NSString stringWithFormat adding a percent [duplicate]NSString stringWithFormat添加百分比[重复]
【发布时间】:2011-01-03 15:51:03
【问题描述】:

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

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

这应该导致字符串为:

40.23%

但事实并非如此。我怎样才能做到这一点?

【问题讨论】:

标签: iphone ios nsstring stringwithformat


【解决方案1】:

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

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

【讨论】:

  • 双精度类型怎么样?
【解决方案2】:

百分号的转义码是“%%”,所以你的代码应该是这样的

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

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

引用自How to add percent sign to NSString

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2010-10-18
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多