Javascript格式浮点数

Javascript格式浮点数,javascript,floating-point,formatting,number-formatting,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 ){ retu

我需要格式化一个数字,使其始终有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,你需要将它们除以1000并加上“K”

如果需要将1000000格式化为1.00M,则可以添加另一个带有“M”后缀的条件


编辑:演示高达万亿:

它们都没有使用floatThank解决3位数的格式设置问题!虽然这里的演示与JSIDdle演示的格式不同,但是在这里它将0.009的格式设置为0.01,但在JSIDdle上正确地设置为0.00one@user59388是的,当使用易于发生浮点数学错误的
Math.floor(num*1000)/1000时,与在JSFIDLE上使用的字符串方法时,会有区别。
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"