这段JS代码自定义了一个可以针对任意小数位的四舍五入函数,使用非常常见,只需要给定要四舍五入的数字,然后给定要四舍五入保留的小数位长度即可。
例如:FormatNumber1(‘23324.5447342’,3),四舍五入后的结果为:23324.545
<html> <head> <title>自定义JS四舍五入函数,脚本分享网 代码片段 http://www.75271.com/codes/</title> <SCRIPT LANGUAGE="javascript"> function FormatNumber1(srcStr,nAfterDot){ var srcStr,nAfterDot; var resultStr,nTen; srcStr = ""+srcStr+""; strLen = srcStr.length; dotPos = srcStr.indexOf(".",0); if (dotPos == -1){ resultStr = srcStr+"."; for (i=0;i<nAfterDot;i++){ resultStr = resultStr+"0"; } return resultStr; } else{ if ((strLen - dotPos - 1) >= nAfterDot){ nAfter = dotPos + nAfterDot + 1; nTen =1; for(j=0;j<nAfterDot;j++){ nTen = nTen*10; } resultStr = Math.round(parseFloat(srcStr)*nTen)/nTen; return resultStr; } else{ resultStr = srcStr; for (i=0;i<(nAfterDot - strLen + dotPos + 1);i++){ resultStr = resultStr+"0"; } return resultStr; } } } </script> </head> <body> <input type="button" value="JS 四舍五入" onclick="alert(FormatNumber1('23324.5447342',3));" /> </body> </html>