Reasons and Solutions for Loss of JS Numerical Precision

outline

1.了解原因
2.解决方案

1. Reason

Because in computers, numbers are converted to binary first, then to arithmetic, and finally to decimal

For example: 0.1 + 0.2

0.1 也就是0.0001100110011001100110011001100110011001100110011001101
0.2 也就是0.001100110011001100110011001100110011001100110011001101

即:
0.00011001100110011001100110011001100110011001100110011010 +
0.0011001100110011001100110011001100110011001100110011010 =
0.0100110011001100110011001100110011001100110011001100111

The result 0.0100110011001100110011001100110011001100110011001100111 and converted to decimal is 0.300000000000000004.

2. Solutions

(1) Plugin Decimal

0.1 + 0.2                                // 0.30000000000000004
x = new Decimal(0.1)
y = x.plus(0.2)                          // '0.3'

(2) Plugin bignumber

x = new BigNumber(0.1)
y = x.plus(0.2)

(3) become an integer

function add(num1, num2) {
    
    
  const num1Len = (num1.toString().split('.')[1] ).length;
  const num2Len = (num2.toString().split('.')[1] ).length;
  const maxLen = Math.pow(10, Math.max(num1Len, num2Len));
  return (num1 * maxLen + num2 * maxLen) / maxLen;
}

おすすめ

転載: blog.csdn.net/weixin_35773751/article/details/126012076