Actual numbers to the human readable values

后端 未结 1 747
陌清茗
陌清茗 2021-02-14 23:31

I have data in bytes. I need to draw this values as human readable labels on a chart (like 2.5KB, 14MB etc.) and need to help with function (input data - actual value, output -

1条回答
  •  名媛妹妹
    2021-02-14 23:42

    I love this implementation: clear and compact:

    function readablizeBytes(bytes) {
        var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
        var e = Math.floor(Math.log(bytes) / Math.log(1024));
        return (bytes / Math.pow(1024, e)).toFixed(2) + " " + s[e];
    }
    

    Usage:

    readablizeBytes(10000000)
    "9.54 MB"
    

    I don't take the credit of this.

    0 讨论(0)
提交回复
热议问题