2015-09-16 55 views
2

我需要格式化一個數字總是有3位,因此數字應該是這樣的的Javascript格式浮點數

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

的數字也應捨去,我無法想出一個有效的方法做這一切,有什麼幫助?

回答

3

對於數字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/

+0

謝謝!雖然這裏的演示格式與jsfiddle演示格式不同,但在這裏它將0.009格式設置爲0.01,但在jsfiddle之一上的格式爲0.00 – user59388

+0

@ user59388是的,使用'Math.floor(num * 1000)/ 1000'時會有差異浮點數學錯誤,以及jsfiddle上使用的字符串方法。 – pawel