当后端给的返回值是小数的时候,前端需要对小数进行处理,得到自己想要的来展示,多数的时候,是保存小数点后面一位或者两位,这个时候,可以使用toFixed() 方法,可把 Number 四舍五入为指定小数位数的数字。
1:保留小数点后面两位
<script type="text/javascript"> let speed=43.3657 console.log(speed.toFixed(2)) </script>
2:保留小数点后面1位
<script type="text/javascript"> let speed=43.3657 console.log(speed.toFixed(1)) </script>
3:保留整数
<script type="text/javascript"> let speed=43.3657 console.log(speed.toFixed(0)) </script>
或者
<script type="text/javascript"> let speed=43.3657 console.log(speed.toFixed()) </script>
实际运用代码
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>toFixed() 方法</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> </head> <body> 速度:<span id="speed"></span> </body> <script type="text/javascript"> $.ajax({ url: "data.json", type: 'GET', dataType: 'json', success: function(data) { //console.log(JSON.stringify(data)) var htm = ""; $.each(data, function(i, item) { htm += '<span >' + item.speed.toFixed(1) + 'km/h</span>'; }) $('#speed').html(htm) } }); </script> </html>
json数据格式,data.json
[{ "speed": 36.6666 }]
保留小数点后面1位,结果如下: