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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor