Input box input value method

pure digital input

// 纯数字
export const onlyNumberInput = (value: string, valid: boolean) => {
    
    
    let result = value || ''
    result = result.replace(/[^\d]/g, '')
    if (valid) {
    
    
        result = result.replace(/^0+(\d)/, '$1') // 第一位0开头,0后面为数字,则过滤掉,取后面的数字
    }
    return result
}

Supports input of integer/decimal/0, and the precision bit is reserved for decimals

/* 
	precision-小数位
	isNegative-是否允许输入负数
*/
export const normalInput = (value: string, precision: string | number, isNegative: boolean) => {
    
    
    let temp = value || ''
    let unit = null,
        result = null
    if (temp.charAt(0) === '-') {
    
    
        unit = temp.slice(0, 1)
        temp = temp.slice(1)
    }
    temp = temp.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
    temp = temp.replace(/^\./g, '') //第一个字符不能是.
    temp = temp.replace(/\.{2,}/g, '.') // 只保留第一个“.”,清除多余的
    temp = temp.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    if (precision) {
    
    
        let nodeIndex = temp.indexOf('.') // 小数点位置
        let pre: number = Number(precision) || 0
        if (nodeIndex != -1) {
    
    
            temp = temp.slice(0, nodeIndex + pre + 1)
        }
        if (temp != '' && temp.indexOf('.') < 0) {
    
    
            temp = String(parseFloat(temp))
        }
    } else {
    
    
        temp = temp.replace(/^0+(\d)/, '$1') // 第一位0开头,0后面为数字,则过滤掉,取后面的数字
    }
    result = unit && isNegative ? unit + temp : temp
    return result
}

Guess you like

Origin blog.csdn.net/Komorebi_00/article/details/131527906