0

I'm trying to combine two Javascript functions into one code. The first function which targets the ".commas" class, inserts a comma after 3 digits. The second called "function floatKey" only allows one decimal point before the last two digits.

I tried inserting the ".commas" class function into the second one and removed the "event.preventDefault if statement", but the result was iffy - it allowed more digits after the decimal along with commas. It also removed all the commas before the decimal point. I also allowed "charCode 44" as an exception to the "if statement" in "function floatKey" but all it did was show and instantly disappear comma inserts. How would I combine these two functions to make both work?

My codes: ".commas" class function:

$(".commas").keyup(function(event){
  if(event.which >= 37 && event.which <= 40){
      event.preventDefault();
  }
  var $this = $(this);
  var num = $this.val().replace(/,/gi, "");
  var num2 = num.split(/(?=(?:\d{3})+$)/).join(",");
  console.log(num2);
  $this.val(num2);
});

function "floatKey":

function floatKey(el, evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var number = el.value.split('.');
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    if(number.length>1 && charCode == 46){
        return false;
    }
    var caratPos = getSelectionStart(el);
    var dotPos = el.value.indexOf(".");
    if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
        return false;
    }
    return true;
}

I hope I explained my problem clear enough, thank you for your help.

codo7081
  • 25
  • 7
  • In the meantime, while responders digest the code and write an answer, you could separate the event handling logic from the string transformation logic. That way you can reason about your problem much easier. (String transformation you can even easilly test too) – Agustín Amenabar Jan 07 '19 at 19:23
  • What is the expected input and output? IE: 123456 becomes 1,234.56 ? – Twisty Jan 07 '19 at 19:28
  • @Twisty Yes - the expected output should be that. – codo7081 Jan 07 '19 at 19:31
  • Or to be more clear, for the input - when a number is typed in input field, a comma is automatically inserted after 3 digits (the first function already does that). The output is automatically generated upon typing as in your example, 1,234.56 – codo7081 Jan 07 '19 at 19:35
  • Please see: https://stackoverflow.com/questions/3753483/javascript-thousand-separator-string-format/19840881 – Twisty Jan 07 '19 at 20:00

1 Answers1

0

Please see: Javascript Thousand Separator / string format

Consider the following.

$(function() {
  function formatFloat(nStr) {
    var result;
    var dec = nStr.indexOf(".");
    var x;
    if (dec > 0) {
      x = nStr.split(".");
      x[0] = parseInt(x[0]);
    } else {
      x = [];
      x.push(parseInt(nStr));
    }
    result = x[0].toLocaleString('en');
    if (dec > 0) {
      result = result + "." + x[1].slice(0,2);
    }
    return result;
  }
  $(".commas").keyup(function(e) {
    e.preventDefault();
    // Strip previous formatting
    var v = $(this).val().split(",").join("");
    // enter new formatting
    $(this).val(formatFloat(v));
    return false;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Number: <input class="commas" type="text" /></p>

In this we split the string if there is a decimal . point. We can use .toLocaleString("en") to localize the number.

The toLocaleString() method returns a string with a language-sensitive representation of this number.

This does all the heavy comma lifting. We then add back the decimal value if needed.

Hope that helps.

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Yes, this resolved everything. Thank you so much for providing me with the code. You've helped me out so much. Much apologies for the late response. – codo7081 Jan 14 '19 at 17:57