<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>JavaScript 精確計算</title>
</head>
<body>
<!-- 你的腳本 -->
<script>
// 自定義高精度浮點數(shù)運算
// 對象格式寫法
var float_calculator = {
/**
* 1.記錄兩個運算數(shù)小數(shù)點后的位數(shù)
* 2.將其轉(zhuǎn)化為整數(shù)類型進行運算
* 3.移動小數(shù)點的位置
**/
add: function(arg1, arg2) {
var r1, r2, m;
try {
//取小數(shù)位長度
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 {
//取小數(shù)位長度
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("計算元數(shù)據(jù):", a , " ", b)
console.log("高精度加法計算結(jié)果: ", float_calculator.add(a , b));
console.log("高精度減法計算結(jié)果: ", float_calculator.minus(a, b));
console.log("高精度乘法計算結(jié)果: ", float_calculator.mul(a, b));
console.log("高精度除法計算結(jié)果: ", float_calculator.div(a, b));
console.log("高精度除法計算:10/3 的結(jié)果為:", float_calculator.div(10, 3));
console.log("高精度除法計算:2/3 的結(jié)果為:", float_calculator.div(2, 3));
</script>
</body>
</html>