如何仅在 JavaScript 中将文件大小转换为 mb?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8471418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert file size to mb only in JavaScript?
提问by Webmaster.Gotactics
How do I convert file size to MB only in JavaScript, It comes back as a long INT sometimes and I would like to convert this to a MB instead of it showing bytes or kb.
如何仅在 JavaScript 中将文件大小转换为 MB,有时它会返回一个 long INT,我想将其转换为 MB,而不是显示字节或 kb。
If possible I would like too also make it show as result like this example("0.01MB"), if it is under the 1 MB.
如果可能的话,我也希望它像这个例子(“0.01MB”)一样显示为结果,如果它低于 1 MB。
回答by devnull69
var sizeInMB = (sizeInBytes / (1024*1024)).toFixed(2);
alert(sizeInMB + 'MB');
回答by Azeem Mirza
Javscript ES5 or earlier:
JavaScript ES5 或更早版本:
function bytesToMegaBytes(bytes) {
return bytes / (1024*1024);
}
Javscript ES6 (arrow functions):
JavaScript ES6(箭头函数):
const bytesToMegaBytes = bytes => bytes / (1024*1024);
If you want to round to exactly digits after the decimal place, then:
如果要四舍五入到小数点后的精确数字,则:
function (bytes, roundTo) {
var converted = bytes / (1024*1024);
return roundTo ? converted.toFixed(roundTo) : converted;
}
In E6 or beyond:
在 E6 或更高版本中:
const bytesToMegaBytes = (bytes, digits) => roundTo ? (bytes / (1024*1024)).toFixed(digits) : (bytes / (1024*1024));
- Details on Number.prototype.toFixed().
- Below you can view file size conversion table, for future help. Conversion table
- Number.prototype.toFixed() 的详细信息。
- 您可以在下方查看文件大小转换表,以备日后帮助。 换算表