2015-10-01 114 views
0

我想將字節轉換爲百分比。百分比將代表已上傳文件的總量。將字節轉換爲百分比

例如,我有:

int64_t totalBytesSent 
int64_t totalBytesExpectedToSend 

我想將其轉換成一個百分比(浮動)。

我已經試過這樣:

int64_t percentage = totalBytesSent/totalBytesExpectedToSend; 

這:

[NSNumber numberWithLongLong:totalBytesSent]; 
[NSNumber numberWithLongLong:totalBytesExpectedToSend]; 
CGFloat = [totalBytesSent longLongValue]/[totalBytesExpectedToSend longLongValue]; 

我覺得我缺少在努力做 '字節數學' 的東西。有誰知道如何將字節轉換爲百分比?

回答

1

你是親近:

int64_t percentage = totalBytesSent/totalBytesExpectedToSend; 

這將返回0和1之間的數字..但是你用整數進行數學運算。鑄造其中之一爲CGFloatfloatdouble等,然後乘以100,或者將之前乘以100 totalBytesSent如果你不想做浮點運算:

int64_t percentage = (double)totalBytesSent/totalBytesExpectedToSend * 100; //uses floating point math, slower 
//or 
int64_t percentage = totalBytesSent*100/totalBytesExpectedToSend; //integer division, faster 

另外,爲什麼你使用int64絕對是一切?你真的需要發送幾十兆字節的數據嗎? unsigned很可能是最好的選擇:

unsigned totalBytesSent 
unsigned totalBytesExpectedToSend 

unsigned percentage = totalBytesSent*100/totalBytesExpectedToSend; 

如果你想在你的百分比小數點,使用浮點運算來劃分,並將結果保存在浮點類型:

CGFloat percentage = totalBytesSent*100/totalBytesExpectedToSend; 
+0

大!這工作!謝謝!我沒有使用int64_t,它是來自塊中第三方庫的參數。 – tentmaking

1

只要將一個整數值(並不重要整數的大小)由一個更大的整數值的結果將始終爲0

要麼分割如果你不之前乘以100的值totalBytesSent在分割之前,不需要小數或將值轉換爲浮點值。

下面的代碼將導致的比例爲0和100之間的值:

int64_t percentage = totalBytesSent*100/totalBytesExpectedToSend;