Javascript字节转KB MB GB TB
字节数字转换为KB、MB、GB、TB
<input type="number" id="byte" value="1024">
<button id="convert-byte">Convert</button>
<div id="preview-size"></div>
<script>
function byte_format(bytes) {
bytes = bytes.toString().replace(/[^0-9.]/g, '');
var sizes = ["B", "KB", "MB", "GB", "TB"];
bytes = parseInt(bytes);
if (bytes <= 0 || isNaN(bytes)) return "0 B";
var i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
document.getElementById("convert-byte").onclick = function(){
let byte = document.getElementById("byte").value;
let result = byte_format(byte);
document.getElementById("preview-size").innerHTML= result
}
</script>
文本内容字节转换
<textarea id="text-val">Lorem ipsum dolor sit amet,....</textarea>
<button id="convert">Convert</button>
<div id="preview-size"></div>
<script>
function byte_format(bytes) {
bytes = bytes.toString().replace(/[^0-9.]/g, '');
var sizes = ["B", "KB", "MB", "GB", "TB"];
bytes = parseInt(bytes);
if (bytes <= 0 || isNaN(bytes)) return "0 B";
var i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
document.getElementById("convert").onclick = function(){
let text = document.getElementById("text-val").value;
var size = new Blob([text]).size;
let result = byte_format(size);
document.getElementById("preview-size").innerHTML= result
}
</script>
版权声明:本文为原创文章,版权归 全栈开发技术博客 所有。
本文链接:https://www.lvtao.net/dev/javascript-byte-size.html
转载时须注明出处及本声明