Javascript 格式 float

标签 javascript floating-point formatting number-formatting

我需要将数字格式化为始终包含 3 位数字,因此数字应如下所示

format(0) -> 0.00
format(1.3456) -> 1.34
format(12) -> 12.0
format(529.96) -> 529
format(12385.123) -> 12.3K

数字也应该向下舍入,我无法找到一种有效的方法来完成这一切,有什么帮助吗?

最佳答案

对于数字 0 - 1000:

function format( num ){
    return ( Math.floor(num * 1000)/1000 )  // slice decimal digits after the 2nd one
    .toFixed(2)  // format with two decimal places
    .substr(0,4) // get the leading four characters
    .replace(/\.$/,''); // remove trailing decimal place separator
}

// > format(0)
// "0.00"
// > format(1.3456)
// "1.34"
// > format(12)
// "12.0"
// > format(529.96)
// "529"

现在,对于数字 1000 - 999 999,您需要将它们除以 1000 并附加“K”

function format( num ){
    var postfix = '';
    if( num > 999 ){
       postfix = "K";
       num = Math.floor(num / 1000);
    }
    return ( Math.floor(num * 1000)/1000 )
    .toFixed(2)
    .substr(0,4)
    .replace(/\.$/,'') + postfix;
}
// results are the same for 0-999, then for >999:
// > format(12385.123)
// "12.3K"
// > format(1001)
// "1.00K"
// > format(809888)
// "809K"

如果您需要将 1 000 000 格式化为 1.00M,那么您可以使用“M”后缀等添加另一个条件。

编辑:演示高达数万亿:http://jsfiddle.net/hvh0w9yp/1/

关于Javascript 格式 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32607604/

相关文章:

python - 如何将有效数字的数量限制为*不超过* str.format() 或 f-strings?

c++ - 仅当当前行溢出 clang 格式时才在新行上加括号

vim - vim 中长段落方便的自动换行

javascript - 使用 ReactJS 中的 AceEditor 了解光标在文本中的位置

javascript - 使用 fetch() 从经过身份验证的 REST 下载和保存数据

javascript - 使用 javascript 变量更改对象高度

iphone - 53 * .01 = .531250

javascript - 使一组输入的值不超过指定值

floating-point - 80 位扩展精度数据类型的应用/好处是什么?

java - 使用 float "possible lossy conversion"的问题