# 好玩的.进位加、乘法

// utils.js
module.exports = {
isFloat(...numOrStrs) {
const POINT_REG = /\./;
return !!numOrStrs.find(item => POINT_REG.test(item));
},
fixLen(a, b, isRight0 = true) {
a += '', b += '';
let diff = a.length - b.length;
const fixStr = '0'.repeat(Math.abs(diff));
if (diff === 0) {
return [a, b];
}
if (isRight0) {
if (diff < 0) {
// b 长
return [fixStr + a, b];
} else {
// a 长
return [a, fixStr + b];
}

} else {
if (diff < 0) {
// b 长
return [a + fixStr, b];
} else {
// a 长
return [a, b + fixStr];
}
}

},
transToInt(num) {
num += '';
const pointIndex = num.indexOf('.');
const diff = num.length - 1 - pointIndex;
return {
move: diff,
value: num.replace(/\./, ''),
};
},
};
// 加法
const utils = require('./utils');
a += '', b += '';
const isFloatMode = utils.isFloat(a, b);
if (!isFloatMode) {
return $add(a, b) * 1; } // 浮点数运算 const [intA, floatA] = a.split('.'); const [intB, floatB] = b.split('.'); let intResult =$add(intA, intB);
let floatResult = $add(floatA, floatB, false); // 处理小数 const floatLenDiff = floatResult.length - Math.max(floatA.length, floatB.length); if (floatLenDiff > 0) { const _int = floatResult.slice(0, floatLenDiff), _float = floatResult.slice(floatLenDiff); intResult =$add(intResult, _int);
floatResult = _float;
}
return (intResult + '.' + floatResult) * 1;
}

function \$add(a, b, isRight0 = true) {
[a, b] = utils.fixLen(a, b, isRight0);
let result = '';
let carryNum = 0;
for (let i = a.length - 1; i >= 0; i--) {
let _r = a[i] * 1 + b[i] * 1 + carryNum;
if (_r >= 10) {
carryNum = 1;
_r -= 10;
} else {
carryNum = 0;
}
result = _r + result;
}
if (carryNum === 1) {
result = '1' + result;
}
return result;
}

// 乘法
const utils = require('./utils');
console.log(1)
function time(a, b) {
a += '', b += '';
let intRate = 1; // 放大倍率
if (utils.isFloat(a)) {
const info = utils.transToInt(a);
a = info.value;
intRate *= Math.pow(10, info.move);
}
if (utils.isFloat(b)) {
const info = utils.transToInt(b);
b = info.value;
intRate *= Math.pow(10, info.move);
}
let results = [];
let post = 0;
for (let i = b.length - 1; i >= 0; i-- , post++) {
results.push(singleTime(a, b[i]) + '0'.repeat(post));
}
let result = 0;
for (let i = 0; i < results.length; i++) {
}
return result / intRate;
}
console.log(time(199.9, 90.5)); // 18090.95
console.log(time(31231.00219, 515.55)); // 16101143.1790545
function singleTime(a, cur) {
let result = '';
let carryNum = 0;
for (let i = a.length - 1; i >= 0; i--) {
let _r = a[i] * cur + carryNum;
if (_r >= 10) {
carryNum = Math.floor(_r / 10);
_r %= 10;
} else {
carryNum = 0;
}
result = _r + result;
}
if (carryNum > 0) {
result = carryNum + result;
}
return result;
}