当前位置:网站首页>Number precision-- use / instance

Number precision-- use / instance

2022-06-09 04:19:00 It blade out of sheath

Original website :number-precision-- Use / example _IT A blog with a sharp blade -CSDN Blog

brief introduction

explain

        This article introduces with examples JavaScript library :number-precision Usage of .

        number-precision Is an exact addition, subtraction, multiplication and division JavaScript library .

Official website

github:https://github.com/nefe/number-precision   (Star Count :3.5K)

npm:https://www.npmjs.com/package/number-precision

Why use number-precision

reason :JS It is not accurate to calculate decimals

example :

All the questions

//  Add 
0.1 + 0.2 = 0.30000000000000004
0.2 + 0.4 = 0.6000000000000001
 
//  Subtraction 
1.5 - 1.2 = 0.30000000000000004
0.3 - 0.2 = 0.09999999999999998
 
//  Multiplication 
19.9 * 100 = 1989.9999999999998
9.7 * 100 = 969.9999999999999
 
//  division  
0.3 / 0.1 = 2.9999999999999996
0.69 / 10 = 0.06899999999999999

 //  Compare 
 0.1 + 0.2 === 0.3 // false
 (0.3 - 0.2) === (0.2 - 0.1) // false

install

npm install number-precision --save

Method

import NP from 'number-precision'

NP.strip(num)         // Turn to the nearest correct number
NP.plus(num1, num2, num3, ...)   // Add :num + num2 + num3, Need at least 2 Parameters
NP.minus(num1, num2, num3, ...)  // Subtraction :num1 - num2 - num3
NP.times(num1, num2, num3, ...)  // Multiplication :num1 * num2 * num3
NP.divide(num1, num2, num3, ...) // division :num1 / num2 / num3
NP.round(num, ratio)  // according to ratio integer

usage

import NP from 'number-precision'

NP.strip(0.09999999999999998); // = 0.1
NP.plus(0.1, 0.2);             // = 0.3, Instead of the original wrong :0.30000000000000004
NP.plus(2.3, 2.4);             // = 4.7, Instead of the original wrong :4.699999999999999
NP.minus(1.0, 0.9);            // = 0.1,  Instead of the original wrong :0.09999999999999998
NP.times(3, 0.3);              // = 0.9, Instead of the original wrong :0.8999999999999999
NP.times(0.362, 100);          // = 36.2, Instead of the original wrong :36.199999999999996
NP.divide(1.21, 1.1);          // = 1.1, Instead of the original wrong :1.0999999999999999
NP.round(0.105, 2);            // = 0.11, Instead of the original wrong :0.1

Be careful

number-precision Is not widely used , Not as good as big.js, bignumber.js, decimal.js.

meanwhile ,number-precision There are very few CDN Provide .

原网站

版权声明
本文为[It blade out of sheath]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090410506097.html