This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript equivalent to printf/string.format
How can I create a Zerofilled value using JavaScript?
I have a number in a variable:
var number = 5;
I need that number to be output as 05:
alert(number); // I want the alert to display 05, rather than 5.
How can I do this?
I could manually check the number and add a 0 to it as a string, but I was hoping there's a JS function that would do it?
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
EDIT:
Meanwhile there is a native JS function that does that. See String#padStart
console.log(String(5).padStart(2, '0'));
Try this
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
alert(pad("5", 2));
Example
http://jsfiddle.net/
Or
var number = 5;
var i;
if (number < 10) {
alert("0"+number);
}
Example
http://jsfiddle.net/
Related
This question already has answers here:
Javascript string/integer comparisons
(9 answers)
Sum of two numbers with prompt
(10 answers)
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
I made a simple js code to input start value and end value form prompt and then find all the odd numbers, unfortunately it's not working properly. when i input 1 and 10 it'll work, but when i input 5 for sValue(start value) the program won't work. any idea?
var odd = [];
var sValue = prompt("start");
var eValue = prompt("end");
for (var i = sValue; i <= eValue; i++) {
if (i % 2 != 0) {
odd.push(i);
}
}
alert(odd);
Because the value of prompt is a string. You need to convert it to a number with parseInt(v, 10).
var odd = [];
var sValue = parseInt(prompt("start"), 10);
var eValue = parseInt(prompt("end"), 10);
for (var i = sValue; i <= eValue; i++) {
if (i % 2 != 0) {
odd.push(i);
}
}
alert(odd);
This question already has answers here:
Want to produce random numbers between 1-45 without repetition
(4 answers)
Closed 4 years ago.
I need help with my code. I want to get 10 random numbers every time it rolls and it can't have duplicated, this is my code:
for(let j = 1; j <= 21; j++) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
I have no idea how I can get exactly 10 numbers every time, anyway it can be written with js or jquery it doesnt metter for me. Hope I can get help here.
I don't really understand what your code is intended to do, but to get exactly 10 unique random numbers I'd use a Set and loop until it's filled. I have no idea why you loop 21 times for 10 items though...
let s = new Set();
while (s.size < 10) {
s.add((Math.floor(Math.random() * 21 /* ??? */) + 1));
}
console.log([...s]);
You're almost there, but instead of using a for loop, use a while loop that continues as long as there are less than 10 things in the array:
const array = [];
const j = 21; // Pick numbers between 1 and 21 (inclusive)
while (array.length < 10) {
const number = (Math.floor((Math.random() * j) + 1))
const genNumber = array.indexOf(number);
if (genNumber === -1) {
array.push(number);
}
}
console.log(array);
goal: take a number like 54321, add the numbers together (5+4+3+2+1 = 15), then take that number (15) add the digits (1+5 = 6), so return 6;
here is my code:
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
}
}
digital_root(1632)
Can't figure out: How to get that function to repeat over and over until digits is just one number (i.e. less than 10). I have tried a variety of nested functions, but can't seem to get it right.
If possible please point me in the direction to the solution ("try a nesting in a while... or read up on..."), but don't give me the complete code solution ("Use this code chunk:...."). I've developed a bad habit of just reading and copying...
Thank you!
Try this: reference HERE
function digital_root(n) {
var singlesum = 0;
while (n >= 10 ) {
singlesum=0;
while (n > 0) {
var rem;
rem = n % 10;
singlesum = singlesum + rem;
n = parseInt(n / 10);
}
n = singlesum;
}
console.log(singlesum);
}
digital_root(1632)
You can use recursion to solve this.
Write a function makeSingleDigit, which argument will be your number.
You need a base condition with the base step, which in your case stops the recursion when received number is one-digit and returns the number.
If condition is not true, you just need to get another digit from the number by n%10 and sum it with the makeSingleDigit(Math.floor(n/10)). By this, you repeatedly sum digits of new numbers, until function receives one-digit number.
Mathematical solution just for your information: the number, which you want to find is n % 9 === 0 ? 9 : n % 9, thus it is the remainder of the division by 9 if it is not 0, otherwise it is 9.
Here is a very optimal solution to the problem:
function digital_root(n) {
return (n - 1) % 9 + 1;
}
const result = digital_root(1632);
console.log(result);
Well, not a very good solution but you can give a hit.
function digital_root(n) {
if (n >=10) {
var digits = n.toString().split('').map(function(item, index) {return parseInt(item)}).reduce(function(a,b){ return a+b});
console.log(digits);
return(digits);
}
}
var num = 1632;
do{
num = digital_root(num);
}while(num>10);
I'm trying to solve a Coderbyte challenge, and I'm still trying to fully understand recursion.
Here's the problem: Using the JavaScript language, have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. For example: if num is 2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.
Here's the solution I put into jsfiddle.net to try out:
function AdditivePersistence(num) {
var count=0;
var sum=0;
var x = num.toString().split('');
for(var i=0; i<x.length; i++) {
sum += parseInt(x[i]);
}
if(sum.length == 1) {
return sum;
}
else {
return AdditivePersistence(sum);
}
}
alert(AdditivePersistence(19));
It tells me that there's too much recursion. Is there another "else" I could put that would basically just re-run the function until the sum was one digit?
One of the problems is that your if statement will never evaluate as 'true'. The reason being is that the sum variable is holding a number, and numbers don't have a length function. Also, as 'Barmar' pointed out, you haven't incremented the count variable, and neither are you returning the count variable.
Here's a solution that works using recursion.
function AdditivePersistence(num) {
var result = recursive(String(num).split('').reduce(function(x,y){return parseInt(x) + parseInt(y)}), 1);
function recursive(n, count){
c = count;
if(n < 10)return c;
else{
count += 1
return recursive(String(n).split('').reduce(function(x,y){return parseInt(x) + parseInt(y)}), count)
}
}
return num < 10 ? 0 : result
}
To fix the 'too much recursion problem',
if(sum.toString().length == 1)
However, as the others have said, your implementation does not return the Additive Persistence. Use James Farrell's answer to solve the Coderbyte challenge.
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 8 years ago.
How can I take a JavaScript integer of arbitrary length, such as 1234567890, and format it as a string "1,234,567,890"?
You can use toLocaleString() for the format that you have asked.
var myNum = 1234567890;
var formattedNum = myNum.toLocaleString();
The best way is probably with a regular expression. From How to print a number with commas as thousands separators in JavaScript:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
My solution:
var number = 1234567890;
var str = number + "";
var result = str.split('').map(function (a, i) {
if ((i - str.length) % 3 === 0 && i !== 0) {
return ',' + a;
} else {
return a;
}
}).join('');
See fiddle.