[英]Convert Bytes to Percentage
I want to convert bytes to a percentage. 我想将字节转换为百分比。 The percentage will represent the total amount a file that has been uploaded.
该百分比将代表已上传文件的总数。
For example, I have: 例如,我有:
int64_t totalBytesSent
int64_t totalBytesExpectedToSend
I want to convert that into a percentage (float). 我想将其转换为百分比(浮动)。
I've tried this: 我已经试过了:
int64_t percentage = totalBytesSent/totalBytesExpectedToSend;
and this: 和这个:
[NSNumber numberWithLongLong:totalBytesSent];
[NSNumber numberWithLongLong:totalBytesExpectedToSend];
CGFloat = [totalBytesSent longLongValue]/[totalBytesExpectedToSend longLongValue];
I think I am missing something in trying to do 'byte-math'. 我想我在尝试做“字节运算”时缺少了一些东西。 Does anyone know how to convert bytes to a percentage?
有谁知道如何将字节转换为百分比?
As long as you divide one integer value (doesn't matter which size of integer) by a bigger integer value the result will always be 0. 只要将一个整数值(与整数的大小无关)除以较大的整数值,结果将始终为0。
Either multiply the totalBytesSent value with 100 before dividing if you don't need decimals or convert values to a floating point value before doing the division. 如果不需要小数,则在除之前将totalBytesSent值乘以100,或者在除之前将值转换为浮点值。
The following code will result in the percentage as a value between 0 and 100: 以下代码将导致百分比的值介于0到100之间:
int64_t percentage = totalBytesSent*100/totalBytesExpectedToSend;
You were close with: 您接近:
int64_t percentage = totalBytesSent/totalBytesExpectedToSend;
This would return a number between 0 and 1...but you're doing math with integers. 这将返回0到1之间的数字...但是您正在使用整数进行数学运算。 Cast one of them to a
CGFloat
, float
, double
, etc, then multiply it by 100, or multiply totalBytesSent
by 100 before dividing if you don't want to do floating-point math: 如果不想进行浮点数学运算,则将其中之一转换为
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
Also, why are you using int64
for absolutely everything? 另外,为什么要对所有内容都使用
int64
? Do you really need to send exabytes of data? 您真的需要发送EB级数据吗?
unsigned
would probably be the best choice: unsigned
可能是最佳选择:
unsigned totalBytesSent
unsigned totalBytesExpectedToSend
unsigned percentage = totalBytesSent*100/totalBytesExpectedToSend;
If you want a decimal point in your percentage, use floating-point math to divide and store the result in a floating-point type: 如果要在百分比中使用小数点,请使用浮点数学将结果除以并以浮点类型存储:
CGFloat percentage = totalBytesSent*100/totalBytesExpectedToSend;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.