acdr-ui/dist/dev/mp-weixin/sheep/helper/digit.js

68 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-09-19 07:20:14 +08:00
"use strict";
function strip(num, precision = 15) {
return +parseFloat(Number(num).toPrecision(precision));
}
function digitLength(num) {
const eSplit = num.toString().split(/[eE]/);
const len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0);
return len > 0 ? len : 0;
}
function float2Fixed(num) {
if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace(".", ""));
}
const dLen = digitLength(num);
return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num);
}
function checkBoundary(num) {
{
if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
console.warn(`${num} 超出了精度限制,结果可能不正确`);
}
}
}
function iteratorOperation(arr, operation) {
const [num1, num2, ...others] = arr;
let res = operation(num1, num2);
others.forEach((num) => {
res = operation(res, num);
});
return res;
}
function times(...nums) {
if (nums.length > 2) {
return iteratorOperation(nums, times);
}
const [num1, num2] = nums;
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
const baseNum = digitLength(num1) + digitLength(num2);
const leftValue = num1Changed * num2Changed;
checkBoundary(leftValue);
return leftValue / Math.pow(10, baseNum);
}
function divide(...nums) {
if (nums.length > 2) {
return iteratorOperation(nums, divide);
}
const [num1, num2] = nums;
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
checkBoundary(num1Changed);
checkBoundary(num2Changed);
return times(
num1Changed / num2Changed,
strip(Math.pow(10, digitLength(num2) - digitLength(num1)))
);
}
function round(num, ratio) {
const base = Math.pow(10, ratio);
let result = divide(Math.round(Math.abs(times(num, base))), base);
if (num < 0 && result !== 0) {
result = times(result, -1);
}
return result;
}
exports.round = round;
//# sourceMappingURL=digit.js.map