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>