This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

JavaScript isn’t perfect and doesn’t affect how it works:

JavaScript isn’t perfect, but that doesn’t stop it from running and being widely used in browsers.

Let’s take a look at some of the features in JavaScript:

0.1 + 0.2! = = = = 0.3 > 0.30000000000000004

0.1 + 0.2 is the direct result of our calculation, while computers store data in binary, and then calculate the binary sum of 0.1 and 0.2.

And 0.1 binary is 0.0001100110011001100… Circulate (1100)

The binary of 0.2 is: 0.00110011001100… (1100 cycle)

MAX_SAFE_INTEGER Specifies the maximum Number that can be expressed accurately in JavaScript: number.max_safe_INTEGER. If it is greater than this safe Number, most integers will not be expressed accurately. The diagram below:

9999999999999999    / / = = > 10000000000000000
Copy the code

Point to the check, still can continue to pursue the end: of course the JavaScript data types and data structures – JavaScript | MDN.

Solve 0.1 + 0.2! == 0.3, set them equal

1. Using native methods:

Number.prototype.tofixed () this method

The toFixed(digits) method uses a fixed point notation to format a number, rounding the result.

numObj.toFixed(digits)
Copy the code

The parameter digits defaults to 0; Represents the number of digits after the decimal point; Between 0 and 20 inclusive, the implementation environment may support a larger range.

2. Using class libraries:math.js

Math.js website: mathjs.org/

Math. Js – NPM package: www.npmjs.com/package/mat…

Lot – warehouse: github-https://github.com/josdejong/mathjs

Solution:

// Import package, use its function method function
const math = require('mathjs')

console.log(math.add(0.1.0.2)) / / 0.30000000000000004

console.log(math.format((math.add(math.bignumber(0.1), math.bignumber(0.2))))) / / '0.3'
Copy the code

Accumulation of learning

Develop the good habit of learning records and make continuous progress!