AI智能
改变未来

JS – 浮点数不精确的解决方案

TOC

前言

js

浮点数的计算存在精度不准的问题,解决方案:用整数与整数的加减乘除运算来规避该问题

JS – 浮点数计算不精确

let [num1,num2] = [0.1, 0.2];console.log(num1 + num2); // 0.30000000000000004console.log(num1 - num2); // -0.1console.log(num1 * num2); // 0.020000000000000004console.log(num1 / num2); // 0.5

解决方案

  • number.js
/*** 加 +* @param num1* @param num2* @returns {number}*/function accAddition(num1, num2) {const num1Digits = (num1.toString().split(\'.\')[1] || \'\').length;const num2Digits = (num2.toString().split(\'.\')[1] || \'\').length;const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));return (Math.round(num1 * baseNum) + Math.round(num2 * baseNum)) / baseNum;}/*** 减 -* @param num1* @param num2* @returns {number}*/function accSubtract(num1, num2) {const num1Digits = (num1.toString().split(\'.\')[1] || \'\').length;const num2Digits = (num2.toString().split(\'.\')[1] || \'\').length;const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));return (Math.round(num1 * baseNum) - Math.round(num2 * baseNum)) / baseNum;}/*** 乘 ** @param num1* @param num2* @returns {number}*/function accMultiply(num1, num2) {const num1Digits = (num1.toString().split(\'.\')[1] || \'\').length;const num2Digits = (num2.toString().split(\'.\')[1] || \'\').length;const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));return (Math.round(num1 * baseNum) * Math.round(num2 * baseNum)) / baseNum / baseNum;}/*** 除 /* @param num1* @param num2* @returns {number}*/function accDivision(num1, num2) {const num1Digits = (num1.toString().split(\'.\')[1] || \'\').length;const num2Digits = (num2.toString().split(\'.\')[1] || \'\').length;const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits));return (Math.round(num1 * baseNum) / Math.round(num2 * baseNum));}export {accAddition,accMultiply,accSubtract,accDivision}

结果验证

import {accAddition, accSubtract, accMultiply, accDivision} from "@/utils/number";let [num1,num2] = [0.1, 0.2];console.log(accAddition(num1, num2)); // 0.3console.log(accSubtract(num1, num2)); // -0.1console.log(accMultiply(num1, num2)); // 0.02console.log(accDivision(num1, num2)); // 0.5

– End -﹀﹀﹀梦想是咸鱼关注一下吧

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » JS – 浮点数不精确的解决方案