0

I need to multiply values from two inputs and put the result into another input. The result needs the commas, but in order to multiply in JavaScript I need to remove the commas from inputs 1 and 2. I tried using the replace() method as well prior to this. I have included my HTML and JS below.

HTML

<div>
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
</div>

JS

$(document).on("input", "#input1, #input2", function () {
    var val1 = parseFloat($("#input1").val());
    var val2 = parseFloat($("#input2").val());
    var total = val1 * val2;
    $("#input3").val(total).trigger("input");
});

2 Answers2

2

First, convert string value in input1 and input2 to float num by removing the commas from it.

Second, do the math as you want.

Third, convert the results back to string then format it with the commas.

Refer:

Remove the commas from a string: https://stackoverflow.com/a/11665949/11392920

Format a number with commas as thousands separators: https://stackoverflow.com/a/2901298/11392920

$(document).on("input", "#input1, #input2", function() {
  var val1 = parseFloat($("#input1").val().replace(/,/g, ''));
  var val2 = parseFloat($("#input2").val().replace(/,/g, ''));
  var total = val1 * val2;
  total = total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  $("#input3").val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input id="input1" type="text" />
  <input id="input2" type="text" />
  <input id="input3" type="text" />
</div>
HVD
  • 231
  • 1
  • 13
0

The first thing that comes to mind is to convert the output to a string and add commas periodically. Here is a code example (where num is the number to display):

var str = num + "";
var output = "";

for (var i = 0; i < str.length; i++) {
    output += str[i];
    if ((str.length - i - 1) % 3 == 0 && i < str.length - 1)
        output += ",";
}
mega12345mega
  • 503
  • 1
  • 6
  • 17