bm-bmt/utils/index.js

85 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 限制输入框中的小数位数
* @param {string} val - 输入值
* @param {number} digit - 小数位位数,默认 2
* @param {boolean} allowNegative - 是否允许负数,默认 false
* @returns {string}
*
* 示例:
* limitDecimal('12.345', 2) // '12.34'
* limitDecimal('12..34', 2) // '12.34'
* limitDecimal('abc123.45', 2) // '123.45'
* limitDecimal('-12.34', 2, true) // '-12.34'
* limitDecimal('007.00', 2) // '7.00'
* limitDecimal('12.5', 0) // '12'digit 为 0 时小数点一并去除,仅保留整数)
*/
export function limitDecimal(val, digit = 2, allowNegative = false) {
if (!val && val !== "0") return "";
// 1. 过滤非法字符
let result = allowNegative
? String(val).replace(/[^\d.-]/g, "")
: String(val).replace(/[^\d.]/g, "");
// 2. 负号只能出现在开头
if (allowNegative) {
const hasMinus = result.indexOf("-") > -1;
result = result.replace(/-/g, "");
if (hasMinus && result) result = "-" + result;
}
// 3. 多个小数点只保留第一个
const parts = result.split(".");
if (parts.length > 2) {
result = parts[0] + "." + parts.slice(1).join("");
}
// 4. 限制小数位数digit 为 0 时去除小数点,仅保留整数)
if (result.includes(".") && digit >= 0) {
const [intPart, decPart] = result.split(".");
result = digit === 0 ? intPart : intPart + "." + decPart.slice(0, digit);
}
// 5. 处理前导零00、01 等
if (
result &&
!result.startsWith("-") &&
result.startsWith("0") &&
result.length > 1 &&
result[1] !== "."
) {
result = result.replace(/^0+/, "");
if (result === "") result = "0";
}
return result;
}
/**
* 数值展示格式化:为 0 时返回 "0.00",非 0 时原样展示
* @param {number|string} num - 原始数值,支持正负值
* @returns {string}
*
* 规则:
* 1. 传入值为 0或空值、非法值返回 "0.00"
* 2. 传入值不为 0无论正负原样返回该值的字符串形式不做任何截取
*
* 示例:
* truncateToTwo(0) // '0.00'
* truncateToTwo('0.0000') // '0.00'
* truncateToTwo(null) // '0.00'
* truncateToTwo('11.0000') // '11.0000'
* truncateToTwo(11.2942) // '11.2942'
* truncateToTwo(-1.239) // '-1.239'
*/
export function truncateToTwo(num) {
const value = Number(num);
// 0、空值、非法值统一返回 0.00
if (!Number.isFinite(value) || value === 0) {
return "0.00";
}
return String(num);
}