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>

标签: Javascript

相关文章

在HTML中为 h1-h6 标签添加序号及颜色背景色块

在HTML结构中,h1 到 h6 是常见的标题标签,通常我们会希望对这些标题进行标注或编号,使其更具层次感。在这篇文章中,我将向您展示如何通过纯JavaScript自动为 h1 到 h6 标签添...

VUE倒计时组件

常用于发送短信、邮件后1分钟倒计时,倒计时结束后又可以再次点击vue组件封装:<template> <div class="timer-btn">...

图片Base64编码

CSR生成

图片无损放大

图片占位符

Excel拆分文件