JSFiddle - React, Tailwind, and code Playground

by lshettyl

HTML

<input type="text" name="number-only" />

JavaScript

$("[name='number-only']").on("change", function() {
    
    var val = "" + this.value;
    if (val.match(/\./g)) { //See if it already has a dot
        if (val.replace(/\./g, "").match(/^\d+$/) !== null) { //Check if it's number after removing the dot
            this.value = parseFloat(val, 10).toFixed(2); //Yes, so format number
        } else {
            //Not a number, so reset the input value
            //Log a msg if need be: "Only numbers allowed!";
            this.value = "";
            this.focus();
        }
    } else {
        //No dot found, so, see if it's a number        
        if (val.match(/^\d+$/) !== null) {
            this.value = parseFloat(val, 10).toFixed(2); //Yes, so format number
        } else {
            //Not a number, so reset the input value
            //Log a msg if need be: "Only numbers allowed!";
            this.value = "";
            this.focus();
        }
    }
});