删除双精度小数点后的字符

时间:2011-12-20 20:02:56

标签: iphone objective-c ios

如何删除小数点后的所有字符。

而不是7.3456,我只想7。

这就是我到目前为止用小数位数来获取数字的方法。

[NSString stringWithFormat:@" %f : %f",(audioPlayer.currentTime),(audioPlayer.duration) ];

非常感谢, -code

9 个答案:

答案 0 :(得分:46)

您可以使用格式字符串指定所需内容:

[NSString stringWithFormat:@" %.0f : %.0f", (audioPlayer.currentTime),
                                            (audioPlayer.duration)];

答案 1 :(得分:4)

floorf()是您正在寻找的功能。

答案 2 :(得分:4)

如果您希望将其显示,请使用NSNumberFormatter

double sevenpointthreefourfivesix = 7.3456;
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithDouble:sevenpointthreefourfivesix]]);
  

2011-12-20 20:19:48.813 NoDecimal [55110:903] 7

如果您想要一个没有小数部分的,请使用round()。如果您希望最接近的整数值不大于原始值,请使用floor()

答案 3 :(得分:3)

转换为int:

[NSString stringWithFormat:@" %i : %i",(int)(audioPlayer.currentTime),(int)(audioPlayer.duration) ];

像这样的转换总是向下舍入(例如:只删除小数点后的所有内容)。这就是你要求的。

在舍入到NEAREST整数的情况下,您希望将0.5添加到数字

[NSString stringWithFormat:@" %i : %i",(int)(audioPlayer.currentTime+0.5f),(int)(audioPlayer.duration+0.5f) ];

这将四舍五入到最接近的整数。例如:1.2变为1.7并且铸造到int使1. 3.6变为4.1并且铸造变为4.:)

答案 4 :(得分:3)

你在追求

[NSString stringWithFormat:@" %.00f : %.00f",(audioPlayer.currentTime),(audioPlayer.duration) ];

格式化浮点数时,您可以通过f

之前的数字来判断精度

答案 5 :(得分:2)

为什么不在使用audioPlayer.currentTime之前将stringWithFormat转换为整数?

[NSString stringWithFormat:@"%d", (int)(audioPlayer.currentTime)];

答案 6 :(得分:0)

您需要做的就是将double类型转换为int,如下所示:int currentTime_int = (int)audioPlayer.currentTime;

您可以对其他变量使用相同的方法。

答案 7 :(得分:0)

这里的许多简短答案都能正常使用。但是如果您希望代码非常清晰和可读,您可能希望明确指定从float到int的所需转换,例如使用:

int tmpInt = floorf(myFloat);  // or roundf(), etc.

然后单独指定您希望如何形成整数,例如

... stringWithFormat:@"%d", tmpInt ...  // or @"%+03d", etc.

而不是假设内联演员表明你想要的东西。

答案 8 :(得分:0)

您也可以使用

  

double newDvalue = floor(dValue);

它将删除所有小数点

使用%.0f作为字符串格式也很好

相关问题