js 四舍五入函数 toFixed(),小数位数精度

时间:2023-03-10 02:05:04
js 四舍五入函数 toFixed(),小数位数精度

js的加减乘除有时得到的结果的小数的位数非常大,这种结果非常难以读取,例如某两个数相乘得到的结果是:1.3921000000000001 这种结果小数的位数有点多,一般需要的结果是四舍无入的 1.39,使用toFixed()函数可以四舍无入:(1.3921000000000001).toFixed(2)得到的结果就是1.39,toFixed()括号的参数就是小数位数。

下面是一些实例代码:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
document.write("<h1>JS保留两位小数例子</h1><br>");
var num = 645.15464000757649;
document.write("原来的值:" + num + "<br>");
document.write("两位小数点:" + num.toFixed(2) + "<br>四位小数点:" + num.toFixed(4));
</script>
</head>
<body>
</body>
</html>

更多toFixed()函数的介绍: http://www.w3school.com.cn/jsref/jsref_tofixed.asp