How do I format a number in Jquery without a plugin?

827 views Asked by At

I have the following code in Jquery for a forn that I am working on:

$(document).ready(function () {
    function RemoveRougeChar(convertString) {
        if (convertString.substring(0, 2) == ".") {
            return convertString.substring(1, convertString.length)
        }
        return convertString;
    }
    $('#float1').on("focus", function (e) {
            var $this = $(this);
            var num = $this.val().replace(/,/g, "");
            $this.val(num);
        })
        .on("blur", function (e) {
            var $this = $(this);
            var num = $this.val().replace(/[^0-9]+/g, '').replace(/,/gi, "").split("").reverse().join("");
            var num2 = RemoveRougeChar(num.replace(/(.{3})/g, "$1,").split("").reverse().join(""));
            $this.val(num2);
        });
});

My HTML :

<input id="float1" decimalPlaces="2" type="text"  style="width:100px;margin-left:5px;"/>

What this does is for example if I type a value of 4461,65 in the field afer the click the value returned is ,446,165. I would like the outcome to be :4,461.65. I read a lot of solutions here on Stackoverflow regarding this and they all hint to the Jquery formatting plugins. I wish to do it without the plugin so I can understand the code better. Is this possible?

1

There are 1 answers

6
ArcangelZith On

Some times basic javascript is the best solution.

 function ModifySelection (textField, value)
 {
        if ('selectionStart' in textField)
        {
            textField.value = [
             textField.value.slice( 0, textField.selectionStart ),
             value,
             textField.value.slice( textField.selectionEnd )
            ].join('');
        }
        else
        {
         // Internet Explorer before version 9
            // create a range from the current selection
            var textRange = document.selection.createRange();

            // check whether the selection is within the textField
            var rangeParent = textRange.parentElement();

            if (rangeParent === textField)
                textRange.text = value;
            else
             textField.value += value;
        }
    }

    var
  // Get decimal separator
  dec_separator = (0.1).toLocaleString().substr(1,1),
  dec_xsanitize = new RegExp('[' + dec_separator + ']', 'g'),
  dec_separator_code = dec_separator.charCodeAt(0),

  // Get thousands separator
  tho_separator = (1000).toLocaleString().substr(1,1),
  tho_xcleaner = new RegExp('[' + tho_separator + ']', 'g'),
  tho_xcleaner_test = new RegExp( tho_xcleaner.source ),

  //
  num_xsanitize = new RegExp('^0+(?=[^' + dec_separator + ']|$)|[^\\d' + dec_separator + ']+', 'g'),
  num_xsanitize_test = new RegExp( num_xsanitize.source );

 $('#float1')
  .on("focus", function ()
  {
   if ( this.value === '0' )
    this.value = '';
   else ( tho_xcleaner_test.test( this.value ) )
    this.value = this.value.replace( tho_xcleaner, '' );
  })
  .on("blur", function ()
  {
   var number = parseFloat(
       this.value
        .replace( tho_xcleaner, '' ) // Clean thousands separator
        .replace( dec_xsanitize, '.' ) // Change decimal separator
       );

   this.value = isNaN(number) ?
       '0'
       :
       number.toLocaleString();
  })
  .on("keypress", function (evt)
  {
   var key = evt.keyCode;

   if ( key === 8 || key > 47 && key < 58 ) // Allow backspace and numbers
    return;

   // Ensuring point once
   if ( key === dec_separator_code )
   {
    // Adding new point reference
    ModifySelection( this, '\t' );

    var value = this.value
        .replace( dec_xsanitize, '' ) // Remove existing points
        .replace( /\t+/g, dec_separator ) // Restore  point reference;

    // Prepend zero if needed
    if ( value[0] === dec_separator )
     value = '0' + value;

    this.value = value;
   }

   // Optional: prepend single minus symbol

   evt.preventDefault(); // Prevent printing
   evt.stopPropagation(); // Kill event now
  })
  .on("input", function ()
  {
   if (num_xsanitize_test.test(this.value))
    this.value = this.value.replace( num_xsanitize, '' );
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="float1" decimalPlaces="2" type="text" />