将字节转换为百分比

时间:2015-10-01 00:15:51

标签: objective-c byte

我想将字节转换为百分比。百分比将代表已上传文件的总金额。

例如,我有:

int64_t totalBytesSent
int64_t totalBytesExpectedToSend

我想将其转换为百分比(浮动)。

我试过这个:

int64_t percentage = totalBytesSent/totalBytesExpectedToSend;

和此:

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

我认为我在尝试'字节数学'时遗漏了一些东西。有谁知道如何将字节转换为百分比?

2 个答案:

答案 0 :(得分:1)

只要将一个整数值(不等于整数的大小)除以更大的整数值,结果将始终为0.

如果您不需要小数或在进行除法之前将值转换为浮点值,则将totalBytesSent值乘以100除以之前除以。

以下代码将导致百分比为0到100之间的值:

int64_t percentage = totalBytesSent*100/totalBytesExpectedToSend;

答案 1 :(得分:1)

你很接近:

int64_t percentage = totalBytesSent/totalBytesExpectedToSend;

这会返回0到1之间的数字......但是你用整数做数学运算。将其中一个投放到CGFloatfloatdouble等,然后将其乘以100,或者将totalBytesSent乘以100,然后再划分,如果您不想做浮点数学:

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

另外,为什么你使用int64绝对是一切?你真的需要发送exabytes的数据吗? unsigned可能是最好的选择:

unsigned totalBytesSent
unsigned totalBytesExpectedToSend

unsigned percentage = totalBytesSent*100/totalBytesExpectedToSend;

如果要在百分比中使用小数点,请使用浮点数学将结果除以浮点类型并存储:

CGFloat percentage = totalBytesSent*100/totalBytesExpectedToSend;