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 !

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Yohan if my answer helped, consider leaving an upvote and/or accepting my answer.
Exact duplicate from this answer: stackoverflow.com/questions/2901102/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.