实际数字与人类可读的值 [英] Actual numbers to the human readable values

查看:63
本文介绍了实际数字与人类可读的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字节数据.我需要将此值绘制为图表上的人类可读标签(例如2.5KB,14MB等),并且需要提供功能方面的帮助(输入数据-实际值,输出-人类可读的字符串).

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 - human readable string).

我做了这样的功能,但是我想要更优雅的实现

I did funcion like this, but I want more elegant realization

function tickFormatter(value, type) {

    var suffix = (type == "bytes") ? ['B', 'KB', 'MB', 'GB'] : ['', 'K', 'M', 'G']

    if(value > (1024 * 1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024 * 1024)).toFixed(2) + suffix[3]
    } else if(value > (1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024)).toFixed(2) + suffix[2]
    } else if (value > (1024 * 1024)) {
        return (value / (1024 * 1024)).toFixed(2) + suffix[1]
    } else {
        return value.toFixed(2) + suffix[0]
    }
}

推荐答案

我喜欢这个实现:简洁明了:

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];
}

用法:

readablizeBytes(10000000)
"9.54 MB"

我不相信这一点.

这篇关于实际数字与人类可读的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆