看到很多人有這保留數字後面小數點的需求,但是大多數是自己寫一個函數來截取,還要考慮四捨五入啥的,寫起來還挺複雜的。
其實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) } |