Valuta di formattazione automatica con Jquery

Formatta automaticamente il campo di input della valuta con virgole e decimali, se necessario. Il testo viene formattato automaticamente con virgole e il cursore viene posizionato nel punto in cui l'utente si era interrotto dopo la formattazione rispetto allo spostamento del cursore alla fine dell'input. La convalida è su KeyUp e una convalida finale viene eseguita su sfocatura.

HTML

<input type="text" class="currency">

JavaScript

$(".currency").on({
    keyup: function() {
        let input_val = $(this).val();
        input_val = numberToCurrency(input_val);
        $(this).val(input_val);
    },
    blur: function() { 
        let input_val = $(this).val();
        input_val = numberToCurrency(input_val, true, true);
        $(this).val(input_val);
    }
});

var numberToCurrency = function (input_val, fixed = false, blur = false) {
    // don't validate empty input
    if(!input_val) {
        return "";
    }
    
    if(blur) {
        if (input_val === "" || input_val == 0) { return 0; }
    }

    if(input_val.length == 1) {
        return parseInt(input_val);
    }

    input_val = ''+input_val;
    
    let negative = '';
    if(input_val.substr(0, 1) == '-'){
        negative = '-';
    }
    // check for decimal
    if (input_val.indexOf(".") >= 0) {
        // get position of first decimal
        // this prevents multiple decimals from
        // being entered
        var decimal_pos = input_val.indexOf(".");

        // split number by decimal point
        var left_side = input_val.substring(0, decimal_pos);
        var right_side = input_val.substring(decimal_pos);

        // add commas to left side of number
        left_side = left_side.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");

        if(fixed && right_side.length > 3) {
            right_side = parseFloat(0+right_side).toFixed(2);
            right_side =  right_side.substr(1, right_side.length);
        }

        // validate right side
        right_side = right_side.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");

        // Limit decimal to only 2 digits
        if(right_side.length > 2) {
            right_side = right_side.substring(0, 2);
        }
    
        if(blur && parseInt(right_side) == 0) {
            right_side = '';
        }

        // join number by .
        // input_val = left_side + "." + right_side;

        if(blur && right_side.length < 1) {
            input_val = left_side;
        } else {
            input_val = left_side + "." + right_side;
        }
    } else {
        // no decimal entered
        // add commas to number
        // remove all non-digits
        input_val = input_val.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    if(input_val.length > 1 && input_val.substr(0, 1) == '0' && input_val.substr(0, 2) != '0.' ) {
        input_val = input_val.substr(1, input_val.length);
    } else if(input_val.substr(0, 2) == '0,') {
        input_val = input_val.substr(2, input_val.length);
    }
    
    return negative+input_val;
};
Demo
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bfotool Demo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <br><br>
                <div class="form-group">
                    <label for="usr">Enter Amount:</label>
                    <input type="text" class="form-control currency">
                </div>
            </div>
        </div>
    </div>

    <script>
        $(".currency").on({
            keyup: function() {
                let input_val = $(this).val();
                input_val = numberToCurrency(input_val);
                $(this).val(input_val);
            },
            blur: function() { 
                let input_val = $(this).val();
                input_val = numberToCurrency(input_val, true, true);
                $(this).val(input_val);
            }
        });

        var numberToCurrency = function (input_val, fixed = false, blur = false) {
            // don't validate empty input
            if(!input_val) {
                return "";
            }
            
            if(blur) {
                if (input_val === "" || input_val == 0) { return 0; }
            }
        
            if(input_val.length == 1) {
                return parseInt(input_val);
            }

            input_val = ''+input_val;
            
            let negative = '';
            if(input_val.substr(0, 1) == '-'){
                negative = '-';
            }
            // check for decimal
            if (input_val.indexOf(".") >= 0) {
                // get position of first decimal
                // this prevents multiple decimals from
                // being entered
                var decimal_pos = input_val.indexOf(".");

                // split number by decimal point
                var left_side = input_val.substring(0, decimal_pos);
                var right_side = input_val.substring(decimal_pos);

                // add commas to left side of number
                left_side = left_side.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");

                if(fixed && right_side.length > 3) {
                    right_side = parseFloat(0+right_side).toFixed(2);
                    right_side =  right_side.substr(1, right_side.length);
                }

                // validate right side
                right_side = right_side.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");

                // Limit decimal to only 2 digits
                if(right_side.length > 2) {
                    right_side = right_side.substring(0, 2);
                }
            
                if(blur && parseInt(right_side) == 0) {
                    right_side = '';
                }

                // join number by .
                // input_val = left_side + "." + right_side;

                if(blur && right_side.length < 1) {
                    input_val = left_side;
                } else {
                    input_val = left_side + "." + right_side;
                }
            } else {
                // no decimal entered
                // add commas to number
                // remove all non-digits
                input_val = input_val.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }

            if(input_val.length > 1 && input_val.substr(0, 1) == '0' && input_val.substr(0, 2) != '0.' ) {
                input_val = input_val.substr(1, input_val.length);
            } else if(input_val.substr(0, 2) == '0,') {
                input_val = input_val.substr(2, input_val.length);
            }
            
            return negative+input_val;
        };
    </script>
</body>
</html>