0

How do I add commas to my output numbers (thousands), and how do I place spaces between 'Step X' and 'the answer' evenly (6 spaces if 'STEPS' is less than 10 and 4 Spaces if 'STEPS' is 10 or greater)?

I know how to add commas to a certain imported number, but how do I do that for all my numbers that are outputed?

This is my code so far:

    <script type = text/javascript>

        // This simple method adds commas to numbers (thousands, millions ...) 

    function formatNumber(num) 
    { 
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") 
    } 
        </script>
    </head>
    <body>
    <h2>Tim Horton Sequence</h2>
    <hr>
    <p>The Tim Horton Sequence is a series of numbers where each value is twice of the preceeding number.<br>
    This will be now known as the 'Double Double'.<br>
   They will show the power of doubling:</p>
    <p>This will show each step starting at the value of <b>ONE (1) times TWO(2)</b>.
    </p>

        <hr>
   <script type = text/javascript>

  function ShowPowersOf(i,j) {
   for (p = 1; p<= j; p += 1){
   document.write("<b>STEP " + p + ":</b> " + p + " * " + i + " = " + Math.pow(i, p)+ "<br/>");
        }

        }


   ShowPowersOf(2,30);
        </script>

This is the formatting instructions/ what I need my code to output

Bob McGee
  • 3
  • 2
  • Possible duplicate of [Javascript Thousand Separator / string format](http://stackoverflow.com/questions/3753483/javascript-thousand-separator-string-format) – Emissary Mar 28 '16 at 16:10
  • Also, check the toLocaleString method in javascript. – user2263572 Mar 28 '16 at 16:11
  • Possible duplicate of [Formatting numbers (decimal places, thousands separators, etc) with CSS](http://stackoverflow.com/questions/8677805/formatting-numbers-decimal-places-thousands-separators-etc-with-css) – Soren Mar 28 '16 at 16:18
  • You certainly could output with some number of spaces following the `STEP #:` portion, but have you considered using a table without borders? – Spencer D Mar 28 '16 at 16:18
  • I am a brand new student and just learned Javascript like a week ago so I am very new at this. What is a table without borders? – Bob McGee Mar 28 '16 at 16:21
  • If the post from Emissary at the top doesn't work this one should: [Numbers with Commas](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript). Easy and efficient to implement. – lovermanthing Mar 28 '16 at 16:37
  • @JessicaMcquaker, all good. I will post an answer so you can see what I mean. – Spencer D Mar 28 '16 at 16:39

2 Answers2

1

Personally, I would use a table with hidden borders for this. A table will allow everything to be neatly formatted without the need to count spaces.

Here is a JSFiddle link to the solution I would use: https://jsfiddle.net/wLwnsgs9/

The following is the Javascript code I am using (based on your code, but revised to match the goal described):

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function ShowPowersOf(i,j) {
    var tbl = document.getElementById("powers");
  tbl.innerHTML = ""; // Clear the inner text

  var lastResult = 1;
  // Loop and output
  for (p = 1; p<= j; p += 1){
    var iResult = lastResult * i; /* calc this iteration's result */

    // Output
    tbl.innerHTML += "<tr><td class='step'>STEP " + p + ":</td><td>" + numberWithCommas(lastResult) + " * " + i + " = " + numberWithCommas(iResult)+ "</td></tr>";

    // Reassign lastResult for next iter
    lastResult = iResult;
  }
}

ShowPowersOf(2,30);

Credits for the numberWithCommas() function to Elias Zamaria from this StackOverflow question

The HTML is pretty simple:

<html>
<body>
  <table id="powers">
  <!-- This will be automatically filled in using Javascript -->
  </table>
</body>
</html>

And then I am using the following CSS just for additional look-and-feel and formatting:

#powers{
  border-collapse: collapse;
}

.step{
  font-weight: bold;
  padding-right: 15px;
}

As you can see from the JSFiddle link, the output seems to be spot-on with the objective you are trying to achieve.

Personally, I would use a table with hidden borders for this. A table will allow everything to be neatly formatted without the need to count spaces.

Here is a JSFiddle link to the solution I would use: https://jsfiddle.net/wLwnsgs9/

The following is the Javascript code I am using (based on your code, but revised to match the goal described):

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function ShowPowersOf(i,j) {
    var tbl = document.getElementById("powers");
  tbl.innerHTML = ""; // Clear the inner text

  var lastResult = 1;
  // Loop and output
  for (p = 1; p<= j; p += 1){
    var iResult = lastResult * i; /* calc this iteration's result */

    // Output
    tbl.innerHTML += "<tr><td class='step'>STEP " + p + ":</td><td>" + numberWithCommas(lastResult) + " * " + i + " = " + numberWithCommas(iResult)+ "</td></tr>";

    // Reassign lastResult for next iter
    lastResult = iResult;
  }
}

ShowPowersOf(2,30);

Credits for the numberWithCommas() function to Elias Zamaria from this StackOverflow question

The HTML is pretty simple:

<html>
<body>
  <table id="powers">
  <!-- This will be automatically filled in using Javascript -->
  </table>
</body>
</html>

And then I am using the following CSS just for additional look-and-feel and formatting:

#powers{
  border-collapse: collapse;
}

.step{
  font-weight: bold;
  padding-right: 15px;
}

As you can see from the JSFiddle link, the output seems to be spot-on with the objective you are trying to achieve.

Note: if you have any questions relating to this answer, please feel free to post a comment and I will try to address them as soon as possible.


EDIT: Revision to prompt a user and ask them how many iterations they would like.

To ask a user how many interations they want, we can use the same basic code, but we will need to make some slight additions and edits to the Javascript.

First, we will need to declare the variable that will hold the number of iterations. We can do so by saying: var iterCount;.

Next we will need to actually get the value from the user. For this we can simply do the following: iterCount = prompt("How many powers would you like to show? (Limit of 30)", "");

Third, we will need a way to check this input value to make sure it is a number and it is within the range limitations. For that, we will need to be a little more complex. Borrowing and tweaking (tweaks/changes are shown in final version) DemoUser's answer from this StackOverflow question, we should be able to achieve this:

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

And then we'll use isNumeric(iterCount) to check if the input is valid.

To handle invalid input, though, we will probably want some way to prompt the user again if the input they give us does not work. For that, we can simply use a while loop with an if-statement. So, putting it all together we get something like this:

function isNumeric(n) {
  return !isNaN(parseInt(n)) && isFinite(n);
}

function getIterCount(){
    var iterCount;
    do{
        iterCount = prompt("How many powers would you like to show? (Limit of 30)", "");
        if(isNumeric(iterCount)){
            // Value is a number
            iterCount = parseInt(iterCount);
            if(iterCount <= 30 && iterCount > 0){
                // Value is in range
                // Exit the loop so we can return the iterCount
                break;
            }
        }
        // If we have not exited the loop at this point, then we know the input was invalid.
        // So, we will show an error message before restarting the loop
        alert("You must enter a number between 1 and 30 (inclusive).\n\nPlease try again.");
    }while(true); // We will perform testing on the var value inside of the loop

    // If we exited the loop, we can presume the user entered in a valid integer, and that
    // valid integer is stored in the iterCount variable. So, we will just return it.
    return iterCount;
}

After that, we simply need to integrate it with the code by replacing ShowPowersOf(2,30); with ShowPowersOf(2, getIterCount());. And we are done.

I have not tested this additional code yet, but it should work. If it does not, let me know. Regardless, it should get you started down the right path.

Community
  • 1
  • 1
Spencer D
  • 3,376
  • 2
  • 27
  • 43
  • Yes the link is exactly what I am looking for. Thank you very much. – Bob McGee Mar 28 '16 at 17:08
  • @JessicaMcquaker, no problem. Glad I could help. Don't forget to upvote and accept this answer if it solved your problem. – Spencer D Mar 28 '16 at 17:23
  • If I wanted to prompt the user to enter how many iterations to output (up to 30), what variable would I set to the prompt command? – Bob McGee Mar 28 '16 at 17:30
  • @JessicaMcquaker, to prompt someone and then check and utilize their input, you would need to define a new variable entirely. I will update my answer momentarily to address that. – Spencer D Mar 28 '16 at 20:13
  • @JessicaMcquaker, additional code added. Please heed the warning at the bottom and let me know if something in the revision does not work. I think it should all work, but there could be typos or minor errors that overlooked when writing that code. – Spencer D Mar 28 '16 at 20:41
  • Yes I tried executing it and does not work. The prompt will come up but will not execute. – Bob McGee Mar 28 '16 at 22:52
  • @JessicaMcquaker, hmm. I'll give it a look in a bit and see if I can figure out what's up with that. – Spencer D Mar 28 '16 at 23:10
  • @JessicaMcquaker, the error was on line 4 of the `getIterCount()` function. Pro-tips: learn to debug by looking at it line-by-line code, and try out your browser's developer tools. This error was easily located by the Chrome Developer Tools' Console: http://i.imgur.com/KUs20dm.png – Spencer D Mar 29 '16 at 00:23
  • I played around with it for a while and I'm surprised I didn't catch that, I will definitely be using Chrome Developer Tools in the future. Thanks again @SpencerDoak – Bob McGee Mar 29 '16 at 00:39
0

You could use the following function to return a string representing the number with commas added:

function formatNumber(num) {
  var arrayOfDigits = String(num).split('');
  var arrLen = arrayOfDigits.length;
  while (arrLen > 3) {
    arrayOfDigits.splice(arrLen - 3, 0, ',');
    arrLen -= 3;
  }
  return arrayOfDigits.join('');
}
document.write(formatNumber(1000000000));
Gary S.
  • 146
  • 5