The solution to the lack of precision in Js decimal operations

Project scenario:

提示:项目需求截图:

Please add a picture description


Problem Description

We all know that when Js is doing calculations 0.1+0.2不等于0.3, the current project needs to calculate the options about the amount, which involves the last two digits of the amount reserved. Policy owed is automatically calculated based on user-entered policy receivables and policy owed.


Cause Analysis:

The reason for the inaccurate calculation accuracy of floating point numbers:
From the perspective of the computer, the computer calculates in binary, not in decimal. After binary, it becomes a wireless non-recurring number, and the computer can support the decimal part of the floating point number up to 52 bits. When all the two are added together and converted into decimal, the obtained number is inaccurate. The principle of addition, subtraction, multiplication and division Same.

Tip: The lack of precision in js decimal calculation is a historical problem, which has been criticized a lot, but there are ways to solve it. js decimal calculation will lose precision, but positive numbers will not have this problem, so when calculating, expand the decimal by the corresponding multiple, so that it becomes Calculated as an integer, and then divide the result by the corresponding multiple to get the desired result.

But I am using the mathjs third-party library here. The following is the solution of mathjs


solution:

Tip: mathjs solution:
official website: https://mathjs.org/index.html

Install

npm install mathjs

introduce

import * as math from 'mathjs'

encapsulated into method

import * as math from 'mathjs';
//例如:num1-num2,在需要的地方直接调用subtract 传二个参数(num1,num2)
    // 加
	add(num1,num2){
    
    
		return math.add(math.bignumber(num1),math.bignumber(num2));
	},
	// 减
	subtract(num1,num2){
    
    
		return math.subtract(math.bignumber(num1),math.bignumber(num2));
	},
	// 乘
	multiply(num1,num2){
    
    
		return math.multiply(math.bignumber(num1),math.bignumber(num2));
	},
	// 除
	divide(num1,num2){
    
    
		return math.divide(math.bignumber(num1),math.bignumber(num2));
}

おすすめ

転載: blog.csdn.net/qq_34082921/article/details/132248750