正确使用cast float to int的百分比?

时间:2012-04-02 18:51:41

标签: objective-c

我正在使用此代码尝试将float转换为int,然后将其用于UILabel文本:

[progLabel setText:[NSString stringWithFormat:@"Deck Progress %i%%",progBar.progress*100]];

我试过这个:

[progLabel setText:[NSString stringWithFormat:@"Deck Progress %i%%",(int)progBar.progress*100]];

显示的文字始终为“0%”。

我也试过这个有效:

int pval=progBar.progress*100;
[progLabel setText:[NSString stringWithFormat:@"Deck Progress %i%%",pval]];

我已经尝试了%f %%但这给了我太多的数字 - 我只想获得0-100,没有小数位。

我做错了什么?

2 个答案:

答案 0 :(得分:3)

(int)仅适用于progBar.progress,因为强制转换的优先级高于乘法,如果0≤progBar.progress< (int)progBar.progress总是0。你需要把整个表达式像

一样
(int)(progBar.progress * 100)

或者,您可以通过使用不显示小数部分的浮点格式来完全避免投射。

[NSString stringWithFormat:@"Deck progress %.0f%%", progBar.progress * 100]

答案 1 :(得分:1)

  

显示的文字始终为“0%”。

这是因为你不是浮动转换为整数:你将浮点数传递给一个毫无疑问的函数期望一个整数。你应该添加一个演员:

[progLabel setText:[NSString stringWithFormat:@"Deck Progress %i%%",(int)(progBar.progress*100)]];