如何實現parseFloat保留小數點后2位


Number.toPrecision(2);
function toPrecision ( [precision : Number] ) : String
參數 
precision 
可選項。有效位數。值必須介於 1 - 21 之間(含 1 和 21)。


備注 
對於以指數記數法表示的數字,將返回小數點后的 precision - 1 位數字。對於以定點記數法表示的數字,將返回 precision 位有效位數。
如果沒有提供參數 precision 或者它為 undefined,則將轉而調用 toString 方法。

要求 
版本 5.5

 

 

應用於:

Number 對象

 


以下是網上其它信息
1:

t.toFixed(2);

2:

t=Math.round(t*100)/100; 
alert(t);

3:

<script> a=3.4534134; alert(parseInt(a*100)/100) </script>

 

補充:

這個方法是在一個例子中看到的,我測試了一下是小數點后四舍五入的功能

例如,5.05---->toFixed(1) 5.1

5.056-------->toFixed(2) 5.06

但是用到0.056時就出現問題了toFixed(1)的結果是0.0

有點奇怪的答案

下面的腳本是重寫了toFixed(),這樣0.056就可以轉化到0.1了

Number.prototype.toFixed=function(len)
{
var add = 0;
var s,temp;
var s1 = this + "";
var start = s1.indexOf(".");
if(s1.substr(start+len+1,1)>=5)add=1;
var temp = Math.pow(10,len);
s = Math.floor(this * temp) + add;
return s/temp;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM