2009-09-22 65 views
3

我正在尋找一種有效的方法來切斷Javascript中很長的浮動數字。我需要這個,因爲我輸出的兩個數字的百分比可能有時像99.4444444,而我只對「。」後面的前兩個數字感興趣。如2號99.44縮短Javascript編號

我目前的百分比回吐功能:

function takePercentage(x,y){ 
    return (x /y) * 100; 
} 

回答

2

如何:

Math.round(myfloatvalue*100)/100 
+0

這與谷歌可視化api表生成工作,而「toFixed(2)」以某種方式沒有。 – Hellnar 2009-09-22 16:18:25

7

您可以使用數。 toFixed

function takePercentage(x,y){ 
    return ((x /y) * 100).toFixed(2); 
} 
+0

注意toFixed無法在IE中概數,可與浮點不精確相結合,會出現意想不到的結果。 – bobince 2009-09-22 17:42:10

2
function takePercentage(x,y){ 
    n = (x /y) * 100; 
    return n.toPrecision(2); 
} 

應該這樣做!

+2

這是不正確的。例如:99.345.toPrecision(2)例如得到「99」 – 2009-09-22 15:48:16

+0

toPresicion返回四捨五入到**有效數字**精度的數字,即:'123.456.toPrecision(3)== 123;','123.456.toPrecision(2 )== 120;','123.456.toPrecision(4)== 123.5;'更多信息在這裏:http://is.gd/3zchw,如果你願意,你也應該使用'var'語句聲明'n'不要n被全局聲明 – CMS 2009-09-22 16:05:28