@ryanuo/utils
Version:
提供多种实用工具函数,涵盖算法、浏览器操作、网络请求等多个领域
96 lines (95 loc) • 2.46 kB
JavaScript
import { Decimal } from "decimal.js";
export const decimal = Decimal;
decimal.set({ precision: 20, rounding: Decimal.ROUND_HALF_UP });
export function preciseAdd(...args) {
return args.reduce(
(sum, num) => sum.plus(new Decimal(num)),
new Decimal(0)
);
}
export function preciseSub(a, b, ...moreNumbers) {
let result = new Decimal(a).minus(new Decimal(b));
for (const num of moreNumbers)
result = result.minus(new Decimal(num));
return result;
}
export function preciseMul(...args) {
if (args.length === 0)
return new Decimal(0);
return args.reduce(
(product, num) => product.times(new Decimal(num)),
new Decimal(1)
);
}
export function preciseDiv(a, b, ...moreDivisors) {
let result = new Decimal(a).dividedBy(new Decimal(b));
for (const num of moreDivisors)
result = result.dividedBy(new Decimal(num));
return result;
}
export function roundTo(num, decimalPlaces = 2) {
if (decimalPlaces < 0)
throw new Error("Decimal places must be a non-negative integer");
return new Decimal(num).toDecimalPlaces(decimalPlaces);
}
export function compare(a, b) {
return new Decimal(a).comparedTo(new Decimal(b));
}
export function calculatePercentage(part, total, options) {
if (Number(total) === 0)
return "NaN";
const { decimalPlaces = 2, isSymbol = false } = options || {};
if (isSymbol) {
return `${preciseDiv(part, total).times(100).toFixed(decimalPlaces)}%`;
} else {
return preciseDiv(part, total).times(100).toFixed(decimalPlaces);
}
}
export class CalculatorChain {
value;
constructor(num) {
this.value = new Decimal(num);
}
/**
* 加法
* @param num 数字或字符串
*/
add(num) {
this.value = this.value.plus(new Decimal(num));
return this;
}
/**
* 减法
* @param num 数字或字符串
*/
sub(num) {
this.value = this.value.minus(new Decimal(num));
return this;
}
/**
* 乘法
* @param num 数字或字符串
*/
mul(num) {
this.value = this.value.times(new Decimal(num));
return this;
}
/**
* 除法
* @param num 数字或字符串
*/
div(num) {
if (Number(num) === 0)
throw new Error("Cannot divide by zero");
this.value = this.value.dividedBy(new Decimal(num));
return this;
}
/**
* round
* @param decimalPlaces 数字或字符串
* @returns Decimal
*/
round(decimalPlaces = 2) {
return this.value.toDecimalPlaces(decimalPlaces);
}
}