how to convert 4000 kilobytes to 4 megabytes in javascript?
i have tried
function formatSizeUnits(bytes){
if (bytes>=1073741824) {bytes=(bytes/1073741824).toFixed(2)+' GB';}
else if (bytes>=1048576) {bytes=(bytes/1048576).toFixed(2)+' MB';}
else if (bytes>=1024) {bytes=(bytes/1024).toFixed(2)+' KB';}
else if (bytes>1) {bytes=bytes+' bytes';}
else if (bytes==1) {bytes=bytes+' byte';}
else {bytes='0 byte';}
return bytes;
}
formatSizeUnits(4000);
Ans I get is "3.91 KB". i need to get 4mb
Your function is correct. It accepts bytes only. But what your trying to do is formatSizeUnits(4000). this is wrong and the expected output is 3.91 MB as it is divided by 1024 and not with 1000. The correct ways is to call like
formatSizeUnits(4000*1024) // beacuse 4000 is in KB and convert into bytes
See the below snippet to get the correct answer
function formatSizeUnits(bytes){
if (bytes>=1073741824) {bytes=(bytes/1073741824).toFixed(2)+' GB';}
else if (bytes>=1048576) {bytes=(bytes/1048576).toFixed(2)+' MB';}
else if (bytes>=1024) {bytes=(bytes/1024).toFixed(2)+' KB';}
else if (bytes>1) {bytes=bytes+' bytes';}
else if (bytes==1) {bytes=bytes+' byte';}
else {bytes='0 byte';}
return bytes;
}
document.write(formatSizeUnits(4000*1024));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With