Calculate download percentage in Objective C
I got stuck with a problem that looked pretty easy but i cant make it work.
I'm making a simple download manager for OSX using objective C. As part of the app im trying to calculate the percentage of the current download. im trying to use this code but it wont wor开发者_StackOverflow中文版k for me
long double precent = (bytesDownloaded/downloadSize) * 100;
NSLog(@"precnt %Lf",precent);
NSLog(@"Downloadedbyret: %lld", bytesDownloaded);
The bytesDownloaded and downloadSize are long long.
Can someone please advise, thanks
To get the correct answer, you must cast the values to long double.
long double precent = ((long double)bytesDownloaded/(long double)downloadSize);
NSLog(@"precnt %Lf",precent);
NSLog(@"Downloadedbyret: %lld", bytesDownloaded);
Is the denominator an int, change it to a floating point? Try:
long double precent = (bytesDownloaded/(downloadSize * 1.0));
NSLog(@"precnt %Lf",precent);
NSLog(@"Downloadedbyret: %lld", bytesDownloaded);
To get % complete you need to multiply by 100.
long double precent = (bytesDownloaded/downloadSize) * 100.0;
if the values bytesDownloaded and downloadSize are int you will need to cast them to a floating point value.
Or if integers multiple the dividend by 100 first:
(bytesDownloaded * 100) / downloadSize;
精彩评论