2

How can I have comma separators displayed in the calculation results? (123456789 to show as 123,456,789)

function calculate(){ a=Number(document.calculator.number1.value); b=Number(document.calculator.number2.value); A1=a*2000 document.calculator.totalA1.value=A1; A2=a*b*240 document.calculator.totalA2.value=A2; A3=a*8*240 document.calculator.totalA3.value=A3; A4=a*960*5 document.calculator.totalA4.value=A4; A5=a*3600*5 document.calculator.totalA5.value=A5; A6=a*3000 document.calculator.totalA6.value=A6; A7=A1+A2+A3+A4+A5+A6 document.calculator.totalA7.value=A7; A8=a*120000 document.calculator.totalA8.value=A8; A9=A8-A7 document.calculator.totalA9.value=A9; } 

I've seen many suggestions but don't know where to insert the script. Thanks!

2
  • 1
    You mean like 2,000? Just stringsplit the number and insert commas every 3 chars. Commented Apr 13, 2016 at 8:44
  • 1
    Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. Commented Apr 13, 2016 at 8:48

2 Answers 2

1

You could try something like this using RegExp

$("#button").click(function(){ var a = 100; var A1=(a*2000); alert(String(A1).replace(/(\d{3})(?!$)/g, "$1,")); })
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <button type="button" id="button">Calculate </button>

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

8 Comments

Interesting solution, too.
Thanks, i've just started learning how regex works so I hope it is indeed a valid solution.
What I wonder is if the regex or the for loop solution is more performant, unfortunately jsperf seems to be down at the moment.
I have no idea haha. From my limited knowledge, i'd assume a loop would be more costly, is that right? I haven't a clue about how how code affects performance yet, I should definitely start reading up on that!
|
0

Here you go: https://jsfiddle.net/odewuqun/3/

function addPunctuation(number){ var array = number.toString().split(""); var output = ""; var first = true; for(var i = array.length-1; i >= 0; i--){ if((array.length-i-1) % 3 === 0){ if(first){ first = false; }else{ output = "," + output; } } output = array[i] + output; } return output; } 

Short explanation:

  • Convert the number into a String.
  • Split that String into an array.
  • Iterate over that array from the end and make a new String where you add a , between every 3 chars.

That is archieved by index % 3 === 0. (% is the mathematic modulo operator for whole number division with rest)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.