compute
# js计算工具
# js浮点数计算
// 浮点数加减乘除 https://blog.csdn.net/mafan121/article/details/81354735
/**
* 浮点数加法
* @param {} a
* @param {*} b
*/
export const floatAdd = function(a, b) {
let m = 0,
n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1] ? d.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
try {
n = e.split(".")[1] ? e.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
let maxInt = Math.pow(10, Math.max(m, n)); //将数字转换为整数的最大倍数
return (floatMul(a, maxInt) + floatMul(b, maxInt)) / maxInt;
};
/**
* 浮点数乘法
* @param {} a
* @param {*} b
*/
export const floatMul = function(a, b) {
let m = 0,
n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1] ? d.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
try {
n = e.split(".")[1] ? e.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
let maxInt = Math.pow(10, m + n); //将数字转换为整数的最大倍数
return (Number(d.replace(".", "")) * Number(e.replace(".", ""))) / maxInt;
};
/**
* 浮点数加法
* @param {} a
* @param {*} b
*/
export const floatDivision = function(a, b) {
let m = 0,
n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1] ? d.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
try {
n = e.split(".")[1] ? e.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
let maxInt = Math.pow(10, Math.max(n, m)); //将数字转换为整数的最大倍数
let aInt = floatMul(a, maxInt);
let bInt = floatMul(b, maxInt);
return aInt / bInt;
};
//小数减法
export const floatSub = (a, b) => {
let m = 0,
n = 0, //记录a,b的小数位数
d = a + "", //字符串化
e = b + "";
try {
m = d.split(".")[1] ? d.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
try {
n = e.split(".")[1] ? e.split(".")[1].length : "";
} catch (error) {
console.log(error);
}
let maxInt = Math.pow(10, Math.max(m, n)); //将数字转换为整数的最大倍数
return (floatMul(a, maxInt) - floatMul(b, maxInt)) / maxInt;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
更新时间: 3/11/2021, 10:44:08 AM