


Detailed explanation of JS floating point number operation processing (graphic tutorial)
This article mainly introduces JS-floating point number operation processing. Now I share it with you and give it as a reference. Interested friends can refer to it.
1. Problem Description
I am working on a project recently. There will be some JS floating point number operations on the page. I found that there are some bugs in JS floating point number operations. For example:
0.1+0.2 == 0.30000000000000004 0.1 + 0.7 == 0.7999999999999999 7*0.8 == 5.6000000000000005 5.6/7 == 0.7999999999999999
2. Solution
There will be a small error after JS operation. Unlike .Net or Java is as accurate as that. The main reason is that the focus of JS is not on calculations, but sometimes projects must use it. After thinking about it, there are probably two solutions
A Solution 1:
Retain the calculation result 2 -3 decimal places. The front-end interface generally uses fewer operations. The accuracy requirements are not too high. So just take 2 decimal places.
B. Option 2:
Convert the number of decimal places to integer operations. For example:
##
0.1+0.2 =》 (1+2)/10 == 0.3 0.1 + 0.7 =》 (1+7)/10 == 0.8 7*0.8 == (7*8)/10 == 5.6 5.6/7 == (56/7)/10 == 0.1In order to facilitate the call, we can extract a public method. For example, in the JSMath library below, JSMath rewrites addition, subtraction, multiplication and division. The parameters will be converted to integers before operation JSMath (parameter 1). Operation (parameter 2) Parameter 1 and parameter 2 are the first Number and the second Number of the operation respectively. After calculation, the value is obtained through the Value attribute.
(function() { var JSMath = function() { return this; } JSMath.prototype.from = function(value) { // 支持JSMath参数传递主要是用于嵌套的调用 if ((typeof(value) == 'object') && (value.value != undefined)) { this.value = value.value; } else { this.value = value; } return this; } // 加法 JSMath.prototype.add = function(value) { var thisValueString = this.value.toString(); var valueString = value.toString(); var timesCount1 = 0; var timesCount2 = 0; if (thisValueString.indexOf('.') > 0) { timesCount1 = thisValueString.split('.')[1].length; } if (valueString.indexOf('.') > 0) { timesCount2 = valueString.split('.')[1].length; } var maxtimeCount = timesCount1 > timesCount2 ? timesCount1 : timesCount2; this.value = (Math.pow(10, maxtimeCount) * this.value + Math.pow(10, maxtimeCount) * value) / Math.pow(10, maxtimeCount); return this; } // 减法 JSMath.prototype.sub = function(value) { var thisValueString = this.value.toString(); var valueString = value.toString(); var timesCount1 = 0; var timesCount2 = 0; if (thisValueString.indexOf('.') > 0) { timesCount1 = thisValueString.split('.')[1].length; } if (valueString.indexOf('.') > 0) { timesCount2 = valueString.split('.')[1].length; } var maxtimeCount = timesCount1 > timesCount2 ? timesCount1 : timesCount2; this.value = (Math.pow(10, maxtimeCount) * this.value - Math.pow(10, maxtimeCount) * value) / Math.pow(10, maxtimeCount); return this; } // 除法 JSMath.prototype.p = function(value) { var thisValueString = this.value.toString(); var valueString = value.toString(); var timesCount1 = 0; var timesCount2 = 0; if (thisValueString.indexOf('.') > 0) { timesCount1 = thisValueString.split('.')[1].length; } if (valueString.indexOf('.') > 0) { timesCount2 = valueString.split('.')[1].length; } var maxtimeCount = timesCount1 > timesCount2 ? timesCount1 : timesCount2; this.value = ((Math.pow(10, maxtimeCount) * this.value) / (Math.pow(10, maxtimeCount) * value)); return this; } // 乘法 JSMath.prototype.times = function(value) { var thisValueString = this.value.toString(); var valueString = value.toString(); var timesCount1 = 0; var timesCount2 = 0; if (thisValueString.indexOf('.') > 0) { timesCount1 = thisValueString.split('.')[1].length; } if (valueString.indexOf('.') > 0) { timesCount2 = valueString.split('.')[1].length; } var maxtimeCount = timesCount1 > timesCount2 ? timesCount1 : timesCount2; this.value = (Math.pow(10, maxtimeCount) * this.value * Math.pow(10, maxtimeCount) * value) / Math.pow(10, maxtimeCount * 2); return this; } if (window.JSMath == undefined) { window.JSMath = function(value) { var result = new JSMath(); result.from(value); return result; } } })()B1.Basic operations
0.1+0.2 => JSMath(0.1).add(0.2).value == 0.3 7+0.8 => JSMath(7).times(0.8).value == 5.6 5.6/7 => JSMath(5.6).p(7).value = 0.8B2. Multi-object operations
0.05 + 0.05 + 0.2 => JSMath(JSMath(0.05).add(0.05)).add(0.2).value == 0.3 (5+0.6)/7 => JSMath(JSMath(5).add(0.6)).p(7).value == 0.8The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. Related articles:
JS Concept and usage instructions of anonymous self-executing functions
p5. How to implement and use js mouse interaction
Summary of js parsing data skills
The above is the detailed content of Detailed explanation of JS floating point number operation processing (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

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.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function