要保留小数点后 N 位的问题,经过一番思索,终于解决了,这篇文章主要介绍了 js 输出数据精确到小数点后 n 位代码,感兴趣的朋友可以参考一下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
1. 借助于 Math.pow(10,n);
2. 借助于 ..toFixed(n) (JS 1.5(IE5.5+,NS6 + 以上版本支持)。
测试 pi=3.14159265 的输出结果:
精确到小数点后 n 位, 借助于 Math.pow(10,n):
3.1
3.14
3.142
3.1416
精确到小数点后 n 位, 借助于 ..toFixed(n):
3.1
3.14
3.142
3.1416
- <html>
- <head>
- <title>
- 四舍五入
- </title>
- <meta charset="utf-8">
- </head>
- <body>
- <script>
- function round_1(num, n) { //返回数字 num, 精确到小数点后 n 位
- var number = Math.round(num * Math.pow(10, n));
- return number / Math.pow(10, n);
- }
- function round_2(num, n) { //返回数字 num, 精确到小数点后 n 位
- return num.toFixed(n); //JS 1.5(IE5.5+,NS6+以上版本支持)
- }
- var pi = 3.14159265;
- document.write("精确到小数点后 n 位, 借助于 Math.pow(10,n):<br>");
- for (var i = 1; i < 5; i++) document.write(round_1(pi, i) + "<br>");
- document.write("精确到小数点后 n 位, 借助于 ..toFixed(n):<br>");
- for (var i = 1; i < 5; i++) document.write(round_2(pi, i) + "<br>");
- </script>
- </body>
- </html>
来源: http://www.phperz.com/article/17/0303/264477.html