1.加法方式

function numAdd(num1: number, num2: number): number{
let baseNum: number, baseNum1: number, baseNum2: number;
try {
baseNum1 = num1.toString().split(".")[1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split(".")[1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
return (num1 * baseNum + num2 * baseNum) / baseNum;
};
2.减法方式

/**
* @param num1被减数
* @param num2减数
*/
function numSub(num1: number, num2: number): number{
let baseNum: number, baseNum1: number, baseNum2: number;
try {
baseNum1 = num1.toString().split(".")[1].length;
} catch (e) {
baseNum1 = 0;
}
try {
baseNum2 = num2.toString().split(".")[1].length;
} catch (e) {
baseNum2 = 0;
}
baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
return (num1 * baseNum - num2 * baseNum) / baseNum;
};

 

例如:numAdd1(283.34,141.67);

function accAddOwn(one,two ,str){
//转化为字符串
one = ''+one
two = ''+two
str = '+'
//切割成整数部分和小数部分
var oneStr = one.split('.')
var twoStr = two.split('.')
// 处理参数一或二为整数的情况
if(!oneStr[1]){
oneStr[1] = ''
}
if(!twoStr[1]){
twoStr[1] = ''
}
var length=null
//比较小数部分的长度,以确定剥离小数点后放大的倍数
var oneFloatLength = oneStr[1].length
var TwoFloatLength = twoStr[1].length
if(oneFloatLength>TwoFloatLength){
length = oneFloatLength
twoStr[1]=twoStr[1].padEnd(length,'0')
} else if(TwoFloatLength>oneFloatLength){
length = TwoFloatLength
twoStr[1]=oneStr[1].padEnd(length,'0')
} else{
length = TwoFloatLength
}
// 拼接成处理后的数字
var oneBig = oneStr[0]+oneStr[1]
var twoBig = twoStr[0]+twoStr[1]

//根据运算符决定运算后缩小的倍数
var result= null
switch(str){
case '+' :;
case '-' : result = eval(oneBig+str+twoBig)/(10**length)
break;
case '*' : result = eval(oneBig+str+twoBig)/(10**(length*2))
break;
case '/' : result = eval(oneBig+str+twoBig)
}
return result; }

是用decimal.js吧

npm install --save decimal.js

 

// 加法

 

new Decimal(a).add(new Decimal(b)) 

 

// 减法

 

new Decimal(a).sub(new Decimal(b))

 

// 乘法

 

new Decimal(a).mul(new Decimal(b))

 

// 除法

 

new Decimal(a).div(new Decimal(b))

 

posted on 2019-08-10 17:08  因过竹林逢僧话  阅读(478)  评论(0编辑  收藏  举报