我有以字节为单位的数据。我需要在图表上将这些值绘制为人类可读的标签(如 2.5KB、14MB 等),并且需要帮助处理功能(输入数据 - 实际值,输出 - 人类可读的字符串)。
我做了这样的功能,但我想要更优雅的实现
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]
}
}