您可以在使用 JavaScript 显示之前发送原始数据并对其进行格式化。见演示:
var MACRO_SCALE = ["", "k", "M", "G", "T"];
var MICRO_SCALE = ["", "d", "c", "m", "µ"];
function formatNumber(n) {
if (n >= 1) {
n = Math.floor(n);
var i = 0;
while (n > 100 && i < MACRO_SCALE.length - 1) {
n /= 1000;
i++;
}
n = Math.round(n) + MACRO_SCALE[i];
} else {
var r = /(\d*)\.([0]*\d{1}?)/.exec(n);
if (r) {
n = r[1] + "." + r[2];
}
var i = 0;
while (n < 1 && i < MICRO_SCALE.length - 1) {
n *= 1000;
i++;
}
n = n + MICRO_SCALE[i];
}
return n;
};
这样做的好处是您可以操纵(如果需要)原始数据,而不是重新转换它。毕竟,数据就是数据,应该只为显示而格式化,除非你真的关心在数据传输中节省几个字节:)
**编辑**
我更新了函数,以便它可以更智能地格式化值(而且我认为MICRO_SCALE
格式化不准确)。这不是白痴证明,但它应该足够接近。查看更新的jsfiddle :
// will not likely to go that high/low, but provided anyway
var MACRO_SCALE = ["", "k", "M", "G", "T" /*, "P", "E", "Z", "Y"*/];
var MICRO_SCALE = ["", "d", "c", "m", "µ" /*, "n", "p", "f", "a"*/];
function formatNumber(n) {
var r = /(\d*)(\.([0]*\d{1}?).*?(e-(\d+))?)?$/.exec(n);
if (r) {
var i = 0;
var scale;
//console.log(r);
if (r[4]) {
scale = MICRO_SCALE;
i = Math.abs(r[5]);
n = r[1];
while (i >= scale.length) {
n /= 10; i--;
}
} else if (r[1] >= 1) {
n = r[1];
scale = MACRO_SCALE;
while (n > 100 && i < scale.length - 1) {
n /= 1000; i++;
}
} else {
n = parseFloat("0." + r[3]);
scale = MICRO_SCALE;
while (n < 1 && i < scale.length - 1) {
n *= 10; i++;
}
}
n += scale[i];
} else {
n = 0;
}
return n;
};
使用这些值和结果进行测试
0.00208239 ==> 2m
1000.77 ==> 1k
abc ==> 0
0.000000342 (or 3.42e-7) ==> 0.003µ
0.0000234 ==> 0.2µ
1 ==> 1
1.2 ==> 1
注意:如果你想得到.2µ
而不是0.2µ
,你所要做的就是将 jsfiddle 的第34行( )替换为:n += scale[i];
n = (n < 1 && n > 0 ? (""+n).substring(1) : n) + scale[i];