How to use matching regularity, you can only enter numbers or negative numbers, but no matter positive or negative numbers only retain one decimal point.

clipboard.png
ask for advice
how to keep the attributes of input and number as decimal points, why can"t the negative sign (-) be entered

Mar.08,2021

let reg = /^-?\d+(\.\d)?$/

/**
 *
 * @param {String} input - 
 * @param {Integer} precision - 1
 * @param {String} type - numberstringundefined"number"
 * @returns {Number|String} type
 */
function demo(input, precision = 1, type = "number") {
    if (typeof input !== "string") {
        try {
            //,
            input = input.toString();
        } catch (error) {
            throw new Error("");
        }
        console.warn("string")
    }
    //precision
    if (!Number.isInteger(precision) || precision < 0) {
        throw new Error("");
    }
    //
    let isMatch = false;
    //:{0,1}?
    const reg = /^-{0,1}\d+(\.\d+){0,1}$/;
    //:replacereturnnumber replace
    const result = input.replace(reg, (match, floatPart) => {
        //true
        isMatch = true;
        //
        const intPart = Math.abs(parseInt(match));
        //,
        const symbol = match.startsWith("-") ? "-" : "";
        //0
        floatPart = floatPart ? parseFloat(parseFloat(floatPart).toFixed(precision)) : 0;
        // 
        return symbol + (intPart + floatPart);
    });
    //
    if (!isMatch) {
        throw new Error("");
    }
    //resulttype
    return type === "number" ? parseFloat(result) : result;
}

clipboard.png


/ ^ -? (([1-9]\ d * (\.\ d {1})? $) | (0\.\ d {1} $) | 0) $/

Menu