数字计算(保留任意精度, 不存在精度丢失, 大值计算,无限制长度) - 码上掘金 (juejin.cn)
function plus(num1: number | string, num2: string) {
const s1 = typeof num1 === 'string' ? num1 : `${num1}`;
const s2 = typeof num1 === 'string' ? num2 : `${num2}`;
const a1 = s1.split('.');
if (a1.length > 2) return NaN;
const a2 = s2.split('.');
if (a2.length > 2) return NaN;
const sn1 = a1.join('');
const sn2 = a2.join('');
const sl = Math.max(a1[1].length, a2[1].length);
const ml = Math.max(sn1.length, sn2.length);
const rl = 12;
const rlc = Math.ceil(ml / rl);
const ns: string[] = [];
for (let i = 0; i < rlc; i++) {
const rn1 = parseInt(sn1.substr(i*rl, rl)) || 0;
const rn2 = parseInt(sn2.substr(i * rl, rl)) || 0;
const pns = typeof ns[i] !== "string" ? 0 : parseInt(ns[i].substring(0, ns[i].length - rl)) || 0;
const rns = (pns + rn1 + rn2).toString();
ns[i] = rns;
}
const rs = ns.join("");
if (sl <= 0) return rs;
return rs.substring(0, rs.length - sl) + '.' + rs.substr(rs.length - sl);
}
console.log(plus('25949420.05635273', '57193472.45773819'));
console.log(plus('25949420.05635273', '57190472.45773819'));
