Reputation: 45
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 !
Upvotes: 0
Views: 29
Reputation: 495
<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.
Upvotes: 2