/** * 处理数字类型方法 * 文档: http://mikemcl.github.io/decimal.js-light/ */ import Decimal from "decimal.js-light" export function toDefaultNumber(n: any): number { return Number(n) || 0 } /** * 1e-11 => "0.00000000001" * @param num * @returns */ export const getFullNum = (num: number | string) => { let result = Number(num) || 0 //处理非数字 if (isNaN(result)) { return result } //处理不需要转换的数字 var str = "" + result if (!/e/i.test(str)) { return result } return result.toFixed(18).replace(/\.?0+$/, "") } /** * 获取小数点后的精度位数 * @param num * @returns */ export const getDecimalNumber = (num: number | string) => { return new Decimal(toDefaultNumber(num)).dp() } /** * 按精度检查输入位 * @param value * @param maxPoint */ export const filterNumAndLimit = (value: number | string, maxPoint = 8) => { value = value.toString() const regExp = new RegExp(`^\\d*(${maxPoint ? "\\." : ""}\\d{0,${maxPoint}})?$`) return regExp.test(value) } /** * 格式化钱,千位加逗号 * @param value */ export const formatMoney = (value: string | number) => { if (!value) return "0" const isNegative = Number(value) < 0 let money = value if (isNegative) { money = value.toString().replace(/\-/g, "") } money = money.toString().replace(/^\d+/g, (s: string) => s.replace(/(?=(?!^)(\d{3})+$)/g, ",")) return isNegative ? `-${money}` : money } /** * 向上取精度 * @param num * @param maxPoint * @returns */ export const formatToCeil = (num: string | number, maxPoint = 8) => { return new Decimal(toDefaultNumber(num)).toFixed(toDefaultNumber(maxPoint), Decimal.ROUND_UP) } /** * 向下按精度格式数据 * @param num * @param maxPoint */ export const formatFloor = (num: string | number, maxPoint: number = 8) => { return new Decimal(toDefaultNumber(num)).toFixed(toDefaultNumber(maxPoint), Decimal.ROUND_DOWN) } /** * 去掉多余的小数点0 * @param num */ export const formatToFloat = (value: any) => { return new Decimal(toDefaultNumber(value)).toFixed() } /**a,b取较小值-lessThanOrEqualTo */ export const decimalMin = (a: number | string, b: number | string) => { return new Decimal(toDefaultNumber(a)).lte(toDefaultNumber(b)) ? a : b } /**a,b取较大值-greaterThanOrEqualTo */ export const decimalMax = (a: number | string, b: number | string) => { return new Decimal(toDefaultNumber(a)).gte(toDefaultNumber(b)) ? a : b } /** * 格式化交易量, 百万M, 十亿B, 千k * @param num */ export function formatMillionMoney(num: string | number, scale: number = 8) { let numNum = Number(num) || 0 // 超过10w格式化文件 if (numNum >= 100000) { const m = parseInt((num || "").toString(), 10) const mLen = m > 0 ? 1 + Math.floor(Math.log10(m)) : 0 let unit: "M" | "B" | "K" | null = null if (mLen >= 10) { // 超过10亿后,用xxx B ,保留两位小数向下取整 numNum = numNum / 1000000000 unit = "B" } else if (mLen >= 7) { // 超过100万后,用xxx M,保留两位小数向下取整 numNum = numNum / 1000000 unit = "M" } else if (mLen >= 6) { // 超过10万后,用xxx K ,保留两位小数向下取整 numNum = numNum / 1000 unit = "K" } const s = numNum.toFixed(unit ? 2 : 0) + " " + (unit || "") return s } return formatFloor(numNum, scale) }