控制保留几位有效小数的js函数
//Code CreateBy abandonship 2007.03.12
function FormatAfterDotNumber( ValueString, nAfterDotNum )
{
var ValueString,nAfterDotNum ;
var resultStr,nTen;
ValueString = ""+ValueString+"";
strLen = ValueString.length;
dotPos = ValueString.indexOf(".",0);
if (dotPos == -1)
{
resultStr = ValueString+".";
for (i=0;i<nAfterDotNum ;i++)
{
resultStr = resultStr+"0";
}
return resultStr;
}
else
{
if ((strLen - dotPos - 1) >= nAfterDotNum ){
nAfter = dotPos + nAfterDotNum + 1;
nTen =1;
for(j=0;j<nAfterDotNum ;j++){
nTen = nTen*10;
}
resultStr = Math.round(parseFloat(ValueString)*nTen)/nTen;
return resultStr;
}
else{
resultStr = ValueString;
for (i=0;i<(nAfterDotNum - strLen + dotPos + 1);i++){
resultStr = resultStr+"0";
}
return resultStr;
}
}
}
应用时只需要FormatAfterDotNumber( '数字字符串', 保留小数位数 );
for example:
<html>
<head>
<SCRIPT LANGUAGE="JAVAscript">
<!--调用上面的函数 -->
</script>
</head>
<body>
<input type="text" name="strTemp">
<input type="button" onclick="alert( FormatAfterDotNumber( document.all. strTemp.value), 保留小数位)" >
</body>
</html>
查看本文来源