mathjs,math.js解决js运算精度问题
程序员文章站
2022-07-05 14:31:38
Document 计算机算数误差: 0.1+0.2 = 0.30000000000000004 17.45*3*0.9 = 47.114999999999995 17.45*0.9*3 = 47.115 用math进行计算,避免误差,见下方js ... ......
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.8.0/math.js"></script> </head> <body> 计算机算数误差: <p>0.1+0.2 = 0.30000000000000004</p> <p>17.45*3*0.9 = 47.114999999999995</p> <p>17.45*0.9*3 = 47.115</p> 用math进行计算,避免误差,见下方js <p> 1. 引入math.js 2.配置number bignumbers较慢但精度较高。大数字的计算仅由算术函数支持。3. 执行计算 </p> <script> math.config({number: 'bignumber'}) console.log(`math--- 0.1+0.2= ${math.eval('0.1+0.2')}`) console.log(`math---17.45*3*0.9 ${math.eval('17.45*3*0.9')}`) console.log(`math---17.45*0.9*3 ${math.eval('17.45*0.9*3')}`) </script> </body> </html>