看到很多人有這保留數字後面小數點的需求但是大多數是自己寫一個函數來截取還要考慮四捨五入啥的寫起來還挺復雜的
其實javascript的Number對象是有一個保留小數點後面的小數的方法的toFixed它是四捨五入後的數
我一度擔心IE不支持這個方法看到MDN裡面說這個方法是javascript才出來專門在IE下試了下是完全支持
toExponential([fractionDigits]) 將數字按科學計數法格式返回其中的fractionDigits值小數點後保留的位數
toFixed([fractionDigits]) 將數字按指定的小數點位數返回其中的fractionDigits值小數點後保留的位數
toPrecision([precision]) 將數字按指定的精度返回(這個精度不是指小數點後幾位)其中precision是指定的精度值
例子如下
代碼如下
var n = ;
ntoFixed(); // Returns
ntoFixed(); // Returns
ntoFixed(); // Returns
(e+)toFixed(); // Returns
(e)toFixed(); // Returns
toFixed(); // Returns
toFixed(); // Returns
()toFixed(); // Returns
轉換函數這段代碼來源於國外一個論壇
代碼如下
function roundNumber(numberdecimals) {
var newString;// The new rounded number
decimals = Number(decimals);
if (decimals < ) {
newString = (Mathround(number))toString();
} else {
var numString = numbertoString();
if (numStringlastIndexOf("") == ) {// If there is no decimal point
numString += "";// give it one at the end
}
var cutoff = numStringlastIndexOf("") + decimals;// The point at which to truncate the number
var d = Number(numStringsubstring(cutoffcutoff+));// The value of the last decimal place that well end up with
var d = Number(numStringsubstring(cutoff+cutoff+));// The next decimal after the last one we want
if (d >= ) {// Do we need to round up at all? If not the string will just be truncated
if (d == && cutoff > ) {// If the last digit is find a new cutoff point
while (cutoff > && (d == || isNaN(d))) {
if (d != "") {
cutoff = ;
d = Number(numStringsubstring(cutoffcutoff+));
} else {
cutoff = ;
}
}
}
d += ;
}
if (d == ) {
numString = numStringsubstring( numStringlastIndexOf(""));
var roundedNum = Number(numString) + ;
newString = roundedNumtoString() + ;
} else {
newString = numStringsubstring(cutoff) + dtoString();
}
}
if (newStringlastIndexOf("") == ) {// Do this again to the new string
newString += "";
}
var decs = (newStringsubstring(newStringlastIndexOf("")+))length;
for(var i=;i
//var newNumber = Number(newString);// make it a number if you like
documentroundformroundedfieldvalue = newString; // Output the result to the form field (change for your purposes)
}
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20632.html