0

I'm using javascript on my website to do simple calculations and the result is supposed to be an amount in dollars, which means that I need that result to contain commas to separate thousands. I tried to apply some solutions I found online but it was difficult to accommodate to my code. Here is what I have:

<script>
 $('#results').hide();
 function multiplyBy()
{
       num1 = document.getElementById("firstNumber").value;
       num2 = document.getElementById("secondNumber").value;
       result = (num2*37)-(num1*4);
       document.getElementById("result").innerHTML = result;
       $('#results').show();
}
</script>

The result is actually in this form XXXXXXX$ and I'd want it to be in that form X,XXX,XXX$

Thanks a lot for reading me !

Yohan
  • 145
  • 1
  • 10

1 Answers1

2
<script>
 $('#results').hide();
 function multiplyBy()
{
       num1 = document.getElementById("firstNumber").value;
       num2 = document.getElementById("secondNumber").value;
       result = (num2*37)-(num1*4);
       document.getElementById("result").innerHTML = result.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
       $('#results').show();
}
</script>

should add the comma separation for you. By the way, the regex is from How to print a number with commas as thousands separators in JavaScript.

ericw31415
  • 415
  • 6
  • 17
  • @Yohan if my answer helped, consider leaving an upvote and/or accepting my answer. – ericw31415 Dec 10 '17 at 01:22
  • Exact duplicate from this answer: https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – Mamun Dec 10 '17 at 01:23