一、问题描述
3.145.toFixed(2) // 3.15
3.155.toFixed(2) // 3.15
3.1551.toFixed(2) // 3.16
3.1550000000000001.toFixed(2) // 3.16
3.15500000000000001.toFixed(2) // 3.15
二、原因分析:
计算机里面存储浮点数二进制浮点数存储的,js是64位的浮点数表示,转化会有精度缺失
三、解决方案:
使用第三方decimal.js
//npm i decimal.jsconst Decimal = require('decimal.js');Decimal(3.155).toFixed(2)