0

i have a text-box that allow only numeric values, and also it is separated with a comma, is working fine, while am using the decimal Separation it's clearing from the first comma field,

Example: Am typing a number:43,553 i need the result :43,553.00 Now am getting result :43.00

please help me to solve this issue

HTML

<input type="text" class="form-control number numericOnly" />

scrip

$(document).ready(function () {

    $("input.number").blur(function () {
        $(this).val(parseFloat($(this).val()).toFixed(2));
    });

    $('input.number').keyup(function(event) {

        // skip for arrow keys
        if(event.which >= 37 && event.which <= 40){
            event.preventDefault();
        }

        $(this).val(function(index, value) {
            value = value.replace(/,/g,'');
            return numberWithCommas(value);
        });
    });

    function numberWithCommas(x) {
        var parts = x.toString().split(".");
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return parts.join(".");
    }
});

$('.numericOnly').keypress(function (event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
      ((event.which < 48 || event.which > 57) &&
        (event.which != 0 && event.which != 8))) {
        event.preventDefault();
    }

    var text = $(this).val();

    if ((text.indexOf('.') != -1) &&
      (text.substring(text.indexOf('.')).length > 2) &&
      (event.which != 0 && event.which != 8) &&
       ($(this)[0].selectionStart >= text.length - 2)) {
        event.preventDefault();
        }
       });

JsFiddle

Divya MV
  • 2,021
  • 3
  • 31
  • 55
Shanu Shaji
  • 134
  • 1
  • 11
  • **[This might help you](http://stackoverflow.com/questions/7571553/javascript-parse-float-is-ignoring-the-decimals-after-my-comma)** – Guruprasad J Rao Aug 12 '15 at 07:02

1 Answers1

1

This happens because of the parseFloat operation. The easiest solution is to replace the comma before casting to float:

$("input.number").blur(function () {
    $(this).val(numberWithCommas(parseFloat($(this).val().replace(/,/g, '')).toFixed(2)));
});

Updated demo

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50