将字节转换为百分比



我想把字节转换成百分比。百分比将表示一个文件已上传的总容量。

例如:

int64_t totalBytesSent
int64_t totalBytesExpectedToSend

我想把它转换成百分比(float)

我试过了:

int64_t percentage = totalBytesSent/totalBytesExpectedToSend;

:

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

我想我在尝试做"字节数学"时遗漏了一些东西。有人知道怎么把字节转换成百分比吗?

你接近了:

int64_t percentage = totalBytesSent/totalBytesExpectedToSend;

这将返回一个介于0到1之间的数字…但你是在用整数做数学。将它们中的一个转换为CGFloat, float, double等,然后将其乘以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 ?你真的需要发送数百万字节的数据吗?unsigned可能是最好的选择:

unsigned totalBytesSent
unsigned totalBytesExpectedToSend
unsigned percentage = totalBytesSent*100/totalBytesExpectedToSend;

如果您希望在百分比中使用小数点,请使用浮点数学进行除法并将结果存储在浮点类型中:

CGFloat percentage = totalBytesSent*100/totalBytesExpectedToSend;

只要你用一个整数值(无论整数大小)除以一个更大的整数值,结果总是0

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

下面的代码将使百分比的值介于0到100之间:

int64_t percentage = totalBytesSent*100/totalBytesExpectedToSend;

最新更新