Reputation: 3
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
Upvotes: 0
Views: 488
Reputation: 3486
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.
Upvotes: 1
Reputation: 146
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));
Upvotes: 0