Javascript -- toFixed()函数

1. toFixed(n) 限制小数点后位数,四舍五入。n:0~20 。

2. 作用对象必须是number,不能为其他类型。如(8.001).toFixed(2)返回8.00;

3. toFixed(n)返回值是String类型,所有当成数字进行比大小是错误的。

4. parseFloat(“number“)与parseInt("number")读取字符串中第一个遇到的数(如91.2w3 第一个数为91.2)并转换为float或int,返回类型为number.

参数如果为字符串类型会报错

复制代码
 1 <!DOCTYPE html>
 2 <html>
 3   <script src="http://code.jquery.com/jquery-latest.js"></script>
 4 <head>
 5   <meta charset="utf-8">
 6   <title>toFixed()</title>
 7 </head>
 8 <body>
 9 </body>
10 <script type="text/javascript">
11   var a0 = 8.01.toFixed()
12   var a1 = parseFloat("8.006").toFixed(2);
13   var a2 = parseFloat("9.091").toFixed(2);
14   document.write("a0类型: "+typeof(a0)+"<br>");
15   document.write("a1类型: "+typeof(a1)+"<br>");
16   document.write("a2类型: "+typeof(a2)+"<br>");
17   document.write("a0: "+a0+"<br>");
18   document.write("a1: "+a1+"<br>");
19   document.write("a2: "+a2+"<br>");
20   document.write("a1 is less than a2 ? : " + (a1 < a2) + "<br>");
21 </script>
22 </html>
复制代码
复制代码
1 输出值:
2 a0类型: string
3 a1类型: string
4 a2类型: string
5 a0: 8
6 a1: 8.01
7 a2: 9.09
8 a1 is less than a2 ? : true  ps:8.01 vs 9.09
复制代码
原文地址:https://www.cnblogs.com/muxueyuan/p/6611535.html