<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>JavaScript 精确计算</title>
</head>
<body>
<!-- 你的脚本 -->
<script>
// 自定义高精度浮点数运算
// 对象格式写法
var float_calculator = {
/**
* 1.记录两个运算数小数点后的位数
* 2.将其转化为整数类型进行运算
* 3.移动小数点的位置
**/
add: function(arg1, arg2) {
var r1, r2, m;
try {
//取小数位长度
r1 = arg1.toString().split(".")[1].length;
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2)); //计算因子
return (arg1 * m + arg2 * m) / m;
},
minus: function(arg1, arg2) {
return this.add(arg1, -arg2);
},
mul: function(arg1, arg2) {
var r1, r2, m;
try {
//取小数位长度
r1 = arg1.toString().split(".")[1].length;
r2 = arg2.toString().split(".")[1].length;
} catch (e) {
r1 = 0;
r2 = 0;
}
m = Math.pow(10, Math.max(r1, r2)); //计算因子
return (arg1 * m) * (arg2 * m) / (m * m);
},
div: function(arg1, arg2) {
if (arg2 == 0) return 0;
var t1 = 0,
t2 = 0,
r1, r2;
try {
var arr1 = arg1.toString().split(".");
var arr2 = arg2.toString().split(".");
t1 = arr1.length == 1 ? 0 : arr1[1].length;
t2 = arr2.length == 1 ? 0 : arr2[1].length;
} catch (e) {
console.log(e);
}
with(Math) {
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
}
return (r1 / r2) * Math.pow(10, t2 - t1);
}
};
let a = 1.11444, b = 23.45674231;
console.log("计算元数据:", a , " ", b)
console.log("高精度加法计算结果: ", float_calculator.add(a , b));
console.log("高精度减法计算结果: ", float_calculator.minus(a, b));
console.log("高精度乘法计算结果: ", float_calculator.mul(a, b));
console.log("高精度除法计算结果: ", float_calculator.div(a, b));
console.log("高精度除法计算:10/3 的结果为:", float_calculator.div(10, 3));
console.log("高精度除法计算:2/3 的结果为:", float_calculator.div(2, 3));
</script>
</body>
</html>