看到很多人有这保留数字后面小数点的需求但是大多数是自己写一个函数来截取还要考虑四捨五入啥的写起来还挺复杂的
其实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)
}