簡體   English   中英

刪除雙精度小數點后的字符

[英]Removing characters after the decimal point for a double

如何刪除小數點后的所有字符。

而不是7.3456,我只想7。

這就是我到目前為止用小數位數來獲取數字的方法。

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

非常感謝,-Code

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

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

如果要將其顯示,請使用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()

floorf()是你正在尋找的功能。

你在追求

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

格式化浮動時,您可以通過f之前的數字來表示精度

轉換為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. :)

為什么不在使用stringWithFormat之前將audioPlayer.currentTime stringWithFormat轉換為整數?

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

你也可以使用

double newDvalue = floor(dValue);

它將刪除所有小數點

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

您需要做的就是將double類型轉換為int,如下所示: int currentTime_int = (int)audioPlayer.currentTime;

您可以對另一個變量使用相同的方法。

這里的許多較短的答案將正常工作。 但是如果您希望代碼非常清晰和可讀,您可能希望明確指定從float到int的所需轉換,例如使用:

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

然后單獨指定如何形成整數,例如

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

而不是假設內聯演員表明你想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM