javascript 數字保留數字後面小數點

來源:互聯網
上載者:User

看到很多人有這保留數字後面小數點的需求,但是大多數是自己寫一個函數來截取,還要考慮四捨五入啥的,寫起來還挺複雜的。

其實javascript的Number對象是有一個保留小數點後面的小數的方法的:toFixed,它是四捨五入後的數。
我一度擔心IE6不支援這個方法,看到MDN裡面說這個方法是javascript1.5才出來。專門在IE6下試了下,是完全支援

toExponential([fractionDigits])   :將數字按科學計數法格式返回,其中的fractionDigits值小數點後保留的位元。

toFixed([fractionDigits])   :將數字按指定的小數點位元返回,其中的fractionDigits值小數點後保留的位元。

toPrecision([precision])   :將數字按指定的精度返回(這個精度不是指小數點後幾位),其中precision是指定的精度值。


例子如下:

 代碼如下 複製代碼

var n = 12345.6789;

n.toFixed();              // Returns 12346

n.toFixed(1);             // Returns 12345.7

n.toFixed(6);             // Returns 12345.678900

(1.23e+20).toFixed(2);    // Returns 123000000000000000000.00

(1.23e-10).toFixed(2);    // Returns 0.00

2.34.toFixed(1);          // Returns 2.3

-2.34.toFixed(1);         // Returns -2.3

(-2.24).toFixed(1);       // Returns -2.2

轉換函式,這段代碼來源於國外一個論壇。

 代碼如下 複製代碼

    function roundNumber(number,decimals) { 
        var newString;// The new rounded number 
        decimals = Number(decimals); 
        if (decimals < 1) { 
            newString = (Math.round(number)).toString(); 
        } else { 
            var numString = number.toString(); 
            if (numString.lastIndexOf(".") == -1) {// If there is no decimal point 
                numString += ".";// give it one at the end 
            } 
            var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number 
            var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with 
            var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want 
            if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated 
                if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point 
                    while (cutoff > 0 && (d1 == 9 || isNaN(d1))) { 
                        if (d1 != ".") { 
                            cutoff -= 1; 
                            d1 = Number(numString.substring(cutoff,cutoff+1)); 
                        } else { 
                            cutoff -= 1; 
                        } 
                    } 
                } 
                d1 += 1; 
            }  
            if (d1 == 10) { 
                numString = numString.substring(0, numString.lastIndexOf(".")); 
                var roundedNum = Number(numString) + 1; 
                newString = roundedNum.toString() + '.'; 
            } else { 
                newString = numString.substring(0,cutoff) + d1.toString(); 
            } 
        } 
        if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string 
            newString += "."; 
        } 
        var decs = (newString.substring(newString.lastIndexOf(".")+1)).length; 
        for(var i=0;i<decimals-decs;i++) newString += "0"; 
        //var newNumber = Number(newString);// make it a number if you like 
        document.roundform.roundedfield.value = newString; // Output the result to the form field (change for your purposes) 
    } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.