2015-10-01 91 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;