bm-bmt/utils/index.js

57 lines
1.7 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;
}