Let's talk about the computational accuracy of js
We all know that using js to do calculations will definitely encounter calculation accuracy problems (or rounding errors), but how to avoid these pitfalls, here is the plan I compiled from the Internet , welcome to discuss.
Reason for loss of accuracy
The binary implementation of the computer and the number of digits limitations some numbers cannot be represented finitely. Just like some irrational numbers cannot be represented finitely, such as pi 3.1415926…, 1.3333… etc. JavaScript uses 64 bits to store numeric types, so any excess is discarded. The omitted part is the part where accuracy is lost.
The following is the binary representation corresponding to the decimal number
0.1 >> 0.0001 1001 1001 1001…(1001无限循环) 0.2 >> 0.0011 0011 0011 0011…(0011无限循环)
Solution
If you need a more complex calculation library, you can consider math.js, etc. Well-known class library
Floating point number (decimal)
For decimals, there are still many chances of problems on the front end, especially in some e-commerce websites involving amounts and other data. Solution: Put the decimal into an integer (multiply the multiple), and then reduce it back to the original multiple (divide the multiple). The operation result after converting to an integer cannot exceed Math.pow(2,53)
// 0.1 + 0.2 (0.1*10 + 0.2*10) / 10 == 0.3 // true
float Point precision operation
/** * floatObj 包含加减乘除四个方法,能确保浮点数运算不丢失精度 * * ** method ** * add / subtract / multiply /divide * * ** explame ** * 0.1 + 0.2 == 0.30000000000000004 (多了 0.00000000000004) * 0.2 + 0.4 == 0.6000000000000001 (多了 0.0000000000001) * 19.9 * 100 == 1989.9999999999998 (少了 0.0000000000002) * * floatObj.add(0.1, 0.2) >> 0.3 * floatObj.multiply(19.9, 100) >> 1990 * */ var floatObj = function() { /* * 判断obj是否为一个整数 */ function isInteger(obj) { return Math.floor(obj) === obj } /* * 将一个浮点数转成整数,返回整数和倍数。如 3.14 >> 314,倍数是 100 * @param floatNum {number} 小数 * @return {object} * {times:100, num: 314} */ function toInteger(floatNum) { var ret = {times: 1, num: 0} if (isInteger(floatNum)) { ret.num = floatNum return ret } var strfi = floatNum + '' var dotPos = strfi.indexOf('.') var len = strfi.substr(dotPos+1).length var times = Math.pow(10, len) var intNum = parseInt(floatNum * times + 0.5, 10) ret.times = times ret.num = intNum return ret } /* * 核心方法,实现加减乘除运算,确保不丢失精度 * 思路:把小数放大为整数(乘),进行算术运算,再缩小为小数(除) * * @param a {number} 运算数1 * @param b {number} 运算数2 * @param digits {number} 精度,保留的小数点数,比如 2, 即保留为两位小数 * @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide) * */ function operation(a, b, digits, op) { var o1 = toInteger(a) var o2 = toInteger(b) var n1 = o1.num var n2 = o2.num var t1 = o1.times var t2 = o2.times var max = t1 > t2 ? t1 : t2 var result = null switch (op) { case 'add': if (t1 === t2) { // 两个小数位数相同 result = n1 + n2 } else if (t1 > t2) { // o1 小数位 大于 o2 result = n1 + n2 * (t1 / t2) } else { // o1 小数位 小于 o2 result = n1 * (t2 / t1) + n2 } return result / max case 'subtract': if (t1 === t2) { result = n1 - n2 } else if (t1 > t2) { result = n1 - n2 * (t1 / t2) } else { result = n1 * (t2 / t1) - n2 } return result / max case 'multiply': result = (n1 * n2) / (t1 * t2) return result case 'divide': result = (n1 / n2) * (t2 / t1) return result } } // 加减乘除的四个接口 function add(a, b, digits) { return operation(a, b, digits, 'add') } function subtract(a, b, digits) { return operation(a, b, digits, 'subtract') } function multiply(a, b, digits) { return operation(a, b, digits, 'multiply') } function divide(a, b, digits) { return operation(a, b, digits, 'divide') } // exports return { add: add, subtract: subtract, multiply: multiply, divide: divide } }();
Usage method:
floatTool.add(a,b);//相加 floatTool.subtract(a,b);//相减 floatTool.multiply(a,b);//相乘 floatTool.divide(a,b);//相除
Super large integer
Although the operation result does not exceed Math.pow(2,53) The above method can also be used for integers (9007199254740992), but if there are more than one, in the actual scenario there may be some batch number, number segment and other requirements. Here I also found a solution, directly enter the code .
Online calculation: https://www.shen.ee/math.html
function compare(p, q) { while (p[0] === '0') { p = p.substr(1); } while (q[0] === '0') { q = q.substr(1); } if (p.length > q.length) { return 1; } else if (p.length < q.length) { return -1; } else { let i = 0; let a, b; while (1) { a = parseInt(p.charAt(i)); b = parseInt(q.charAt(i)); if (a > b) { return 1; } else if (a < b) { return -1; } else if (i === p.length - 1) { return 0; } i++; } } } function divide(A, B) { let result = []; let max = 9; let point = 5; let fill = 0; if (B.length - A.length > 0) { point += fill = B.length - A.length; } for (let i = 0; i < point; i++) { A += '0'; } let la = A.length; let lb = B.length; let b0 = parseInt(B.charAt(0)); let Adb = A.substr(0, lb); A = A.substr(lb); let temp, r; for (let j = 0; j < la - lb + 1; j++) { while (Adb[0] === '0') { Adb = Adb.substr(1); } if (Adb.length === lb) { max = Math.ceil((parseInt(Adb.charAt(0)) + 1) / b0); // 不可能取到这个最大值,1<= max <= 10 } else if (Adb.length > lb) { max = Math.ceil((parseInt(Adb.substr(0, 2)) + 1) / b0); } else { result.push(0); Adb += A[0]; A = A.substr(1); continue; } for (let i = max - 1; i >= 0; i--) { if (i === 0) { result.push(0); Adb += A[0]; A = A.substr(1); break; } else { temp = temp || multiply(B, i + ''); r = compare(temp, Adb); if (r === 0 || r === -1) { result.push(i); if (r) { Adb = reduce(Adb, temp); Adb += A[0]; } else { Adb = A[0]; } A = A.substr(1); break; } else { temp = reduce(temp, B); } } } temp = 0; } for (let i = 0; i < fill; i++) { result.unshift('0'); } result.splice(result.length - point, 0, '.'); if (!result[0] && result[1] !== '.') { result.shift(); } point = false; let position = result.indexOf('.'); for (let i = position + 1; i < result.length; i++) { if (result[i]) { point = true; break; } } if (!point) { result.splice(position); } result = result.join(''); return result; } function multiply(A, B) { let result = []; (A += ''), (B += ''); const l = -4; // 以支持百万位精确运算,但速度减半 let r1 = [], r2 = []; while (A !== '') { r1.unshift(parseInt(A.substr(l))); A = A.slice(0, l); } while (B !== '') { r2.unshift(parseInt(B.substr(l))); B = B.slice(0, l); } let index, value; for (let i = 0; i < r1.length; i++) { for (let j = 0; j < r2.length; j++) { value = 0; if (r1[i] && r2[j]) { value = r1[i] * r2[j]; } index = i + j; if (result[index]) { result[index] += value; } else { result[index] = value; } } } for (let i = result.length - 1; i > 0; i--) { result[i] += ''; if (result[i].length > -l) { result[i - 1] += parseInt(result[i].slice(0, l)); result[i] = result[i].substr(l); } while (result[i].length < -l) { result[i] = '0' + result[i]; } } if (result[0]) { result = result.join(''); } else { result = '0'; } return result; } function add(A, B) { let result = []; (A += ''), (B += ''); const l = -15; while (A !== '' && B !== '') { result.unshift(parseInt(A.substr(l)) + parseInt(B.substr(l))); A = A.slice(0, l); B = B.slice(0, l); } A += B; for (let i = result.length - 1; i > 0; i--) { result[i] += ''; if (result[i].length > -l) { result[i - 1] += 1; result[i] = result[i].substr(1); } else { while (result[i].length < -l) { result[i] = '0' + result[i]; } } } while (A && (result[0] + '').length > -l) { result[0] = (result[0] + '').substr(1); result.unshift(parseInt(A.substr(l)) + 1); A = A.slice(0, l); } if (A) { while ((result[0] + '').length < -l) { result[0] = '0' + result[0]; } result.unshift(A); } if (result[0]) { result = result.join(''); } else { result = '0'; } return result; } function reduce(A, B) { let result = []; (A += ''), (B += ''); while (A[0] === '0') { A = A.substr(1); } while (B[0] === '0') { B = B.substr(1); } const l = -15; let N = '1'; for (let i = 0; i < -l; i++) { N += '0'; } N = parseInt(N); while (A !== '' && B !== '') { result.unshift(parseInt(A.substr(l)) - parseInt(B.substr(l))); A = A.slice(0, l); B = B.slice(0, l); } if (A !== '' || B !== '') { let s = B === '' ? 1 : -1; A += B; while (A !== '') { result.unshift(s * parseInt(A.substr(l))); A = A.slice(0, l); } } while (result.length !== 0 && result[0] === 0) { result.shift(); } let s = ''; if (result.length === 0) { result = 0; } else if (result[0] < 0) { s = '-'; for (let i = result.length - 1; i > 0; i--) { if (result[i] > 0) { result[i] -= N; result[i - 1]++; } result[i] *= -1; result[i] += ''; while (result[i].length < -l) { result[i] = '0' + result[i]; } } result[0] *= -1; } else { for (let i = result.length - 1; i > 0; i--) { if (result[i] < 0) { result[i] += N; result[i - 1]--; } result[i] += ''; while (result[i].length < -l) { result[i] = '0' + result[i]; } } } if (result) { while ((result[0] = parseInt(result[0])) === 0) { result.shift(); } result = s + result.join(''); } return result; }
Instructions for use: Negative numbers are not allowed, and it is best to use strings for parameters
divide(A,B) // 除法 multiply(A,B) //乘法 add(A,B) //加法 reduce(A,B) //减法
toFixed's fix
In Firefox/Chrome, toFixed does not round the last digit of 5 as expected.
1.35.toFixed(1) // 1.4 正确 1.335.toFixed(2) // 1.33 错误 1.3335.toFixed(3) // 1.333 错误 1.33335.toFixed(4) // 1.3334 正确 1.333335.toFixed(5) // 1.33333 错误 1.3333335.toFixed(6) // 1.333333 错误
There is no problem with the implementation of Firefox and Chrome. The root cause is the loss of precision of floating point numbers in the computer.
Repair method:
function toFixed(num, s) { var times = Math.pow(10, s) var des = num * times + 0.5 des = parseInt(des, 10) / times return des + '' }
This article has ended here. For more other exciting content, you can pay attention to the JavaScript video tutorial on the PHP Chinese website Column!
The above is the detailed content of Let's talk about the computational accuracy of js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

As a popular server-side scripting language, PHP often encounters problems of loss of precision or calculation errors when performing floating-point calculations. These problems may affect the accuracy and stability of the program. This article will explore the causes of PHP floating point calculation errors, propose some avoidance strategies, and give specific code examples for reference. 1. Reasons for PHP floating-point calculation errors. In computers, floating-point numbers are represented in binary form, and binary cannot accurately represent all decimal decimals, which leads to the inaccuracy of floating-point numbers.
