<script type="text/javascript">
//两数相加
function numadd(a, b) {
a = isNaN(a) ? 0 : a
b = isNaN(b) ? 0 : b
var c, d, e;
try {
c = a.toString().split(".")[1].length;
} catch (f) {
c = 0;
}
try {
d = b.toString().split(".")[1].length;
} catch (f) {
d = 0;
}
return e = Math.pow(10, Math.max(c, d)), (nummul(a, e) + nummul(b, e)) / e;
}
//两数相乘
function nummul(a, b) {
a = isNaN(a) ? 0 : a
b = isNaN(b) ? 0 : b
var c = 0,
d = a.toString(),
e = b.toString();
try {
c += d.split(".")[1].length;
} catch (f) {
f == f
}
try {
c += e.split(".")[1].length;
} catch (f) {
f == f
}
return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}
//两数相减
function numsub(a, b) {
a = isNaN(a) ? 0 : a
b = isNaN(b) ? 0 : b
var c, d, e;
try {
c = a.toString().split(".")[1].length;
} catch (f) {
c = 0;
}
try {
d = b.toString().split(".")[1].length;
} catch (f) {
d = 0;
}
return e = Math.pow(10, Math.max(c, d)), (nummul(a, e) - nummul(b, e)) / e;
}
/**
* 两数相除
* @param a 被除数
* @param b 除数
* @returns {*}
*/
function numdiv(a, b) {
a = isNaN(a) ? 0 : a
b = isNaN(b) ? 0 : b
var c, d, e = 0,
f = 0;
try {
e = a.toString().split(".")[1].length;
} catch (g) {
g == g
}
try {
f = b.toString().split(".")[1].length;
} catch (g) {
g == g
}
return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), nummul(c / d, Math.pow(10, f - e));
}
$(function(){
alert(numadd(1.414,1.732));
alert(nummul(1.732,1.4146));
alert(numsub(1.414,1.732));
alert(numdiv(1.732,1.4146));
});
</script>
Js 实现两个小数的相乘、相除、相加和相减功能
于 2022-07-27 14:34:15 首次发布