javascriptjquerymathjs

Dynamic floating decimal point in Javascript


I am creating a general ledger application in javascript and want to dynamically shift a number to two decimal places as an input that number. It should happen when someone starts typing a number into a HTML input text field; I want it to work like an onKeyUp or onKeyPress event.

Examples:

  1. I type "1" and the output will be "0.01"
  2. I type "12" and the output will be "0.12"
  3. I type "123" and the output will be "1.23"
  4. I type "1234" and the output will be "12.34"

I have looked through jquery, mathjs, and have yet to find something.

Can anybody please give me some guidance?

Thank you in advance!


Solution

  • $(document).ready(function() {
      var value = '';
      $('input').on('keyup', function(e) {
        if (e.which != 8 && isNaN(String.fromCharCode(e.which))) {
          e.preventDefault();
          return;
        }
        if ($(this).val() == 0.00) value = '';
        if (e.keyCode == 8) {
          value = value.slice(0, -1)
        } else {
          value += e.key
        };
        var sss = (value / 100).toFixed(2);
        if (sss == "0.00")
          $(this).val('');
        else
          $(this).val(sss);
      })
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type=number>