How to add a comma in my increasing number via JS? [duplicate] - javascript

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 8 years ago.
I'm trying to add a comma between my 20000 to show as 20,000 without it messing up and have gotten pretty close but trying to fill in the next steps. Below, I've listed my code with the function thats able to do it but trying to connect the two together to properly work.
Here is my jsFiddle!
And code..
HTML
<span id="liveNumbers">23000</span>
JS
setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus;
currentnumber = document.getElementById('liveNumbers');
document.getElementById('liveNumbers').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 3000);
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}

You'd have to change your initial value to include a comma or do an initial run before the setInterval is started but something like this might work:
setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus;
currentnumber = document.getElementById('liveNumbers');
var curnum = parseInt(currentnumber.innerHTML.replace(",",""));
document.getElementById('liveNumbers').innerHTML =
commaSeparateNumber(curnum + random);
}, 3000);
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}

Related

How do I make this function a number? [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed last year.
I'm learning JavaScript and I wanted to accept user input and add a number to it ,but instead of outputting 12+12 = 24 it's outputting 12+ 12 = 1212.
document.getElementById("mybutton").onclick = function(){
var myAge = document.getElementById("mytext").value + 12;
document.getElementById("value").innerHTML = myAge;
}
I tried doing:
myName = Number(myName)
but it didn't work
In this case use a function parseInt()
example:
document.getElementById("mybutton").onclick = function(){
var myAge = parseInt(document.getElementById("mytext").value) + 12;
document.getElementById("value").innerHTML = myAge;
}

Reverse Integer Without converting to a string Javascript? [duplicate]

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 2 years ago.
So i am trying to reverse an integer and so far the code works but i am trying to find a solution to reverse the integer without converting into a string first? Any help would be appreciated. This is my code snippet so far to reverse the integer.
function reverseInt(num) {
const reversed = num.toString().split('').reverse().join('')
return parseInt(reversed) * Math.sign(num)
}
console.log(reverseInt(-500));
I am trying to do it using javascript.
Try this:
function reverseInt(number) {
var isNegative = number < 0 ? true : false;
if(isNegative)
number = number * -1;
var reverse = 0, lastDigit = 0;
while (number >= 1) {
reverse = Math.floor(reverse * 10 + (number % 10));
number = number / 10;
}
return isNegative == true ? reverse*-1 : reverse;
}
console.log(reverseInt(-500));
console.log(reverseInt(501));

Padding zero to the left of number in Javascript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 8 years ago.
I have a ten digit number that will always be constant. I want to pad it so, that it will always remove a zero for every extra number added to the number. Can someone please show me an example of how I can do this?
eg. 0000000001
0000000123
0000011299
You can use this function:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
Output
pad("123", 10); // => "0000000123"
JSFIDDLE DEMO
Just try with:
function zeroPad(input, length) {
return (Array(length + 1).join('0') + input).slice(-length);
}
var output = zeroPad(123, 10);
Output:
"0000000123"
Another variant would be:
function pad(input, length) {
return Array(length - Math.floor(Math.log10(input))).join('0') + input;
}
var out = pad(23, 4); // is "0023"

Can't figure out parseInt, even after research in JS and JQ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have an object with a property containing a large string. This property has a value with random numbers generated earlier in the script in the format x , x , x , x ... (isn't and can't be an array because of other needs for the variable within the program) and so on. I am trying to get the sum of these numbers and my first thought was to use parseInt() to do this by splitting them all up then adding them together, but when I do this it only returns the first number. Is this what I should do but I'm just doing it wrong? Or is there another function that would make this easier?
The program is a blackjack game I'm making to see how well i understand everything I am learning.
Here is the function i am trying to make to see if the user busts when taking a hit (not much so far because i can't figure out the parseInt thing)
'
function checkBust() {
var total = parseInt(user.hand, 10);
}
'
the user object
'
var user = {
hand: dealUser()
};
'
and the functions to set the object property
function randomCard() {
// random number between 0 and 10
var j = Math.random() * 10;
// round that number into a var called card
var card = Math.round(j);
// if card is 0, assign a J Q or K by making a random number again
if (card === 0) {
//another random number
var k = Math.random() * 10;
// checks random number and assign J Q or K
if (k <= 4) {
card = 'J';
} else if (k <= 7) {
card = 'Q';
}
else {
card = 'K';
}
}
// value of the function is a single card
return card;
}
function dealUser() {
// empty array to store cards
var x = [];
// var to start for loop
var i = 0;
// start for loop
for (i; i < 2; i++) {
// add a random card to the i^th index of x
x[i] = randomCard();
}
// value for function is array of two cards x[0] , x[1]
var cards = x[0] + " , " + x[1];
return cards;
}
parseInt will stop parsing when it reaches a non numeric character.
parseInt('1234,5678', 10); // => 1234
// since a comma (,) is not a numeric character, everything after is ignored.
You have to split the string into an array of strings using the comma as the delimiter:
'1234,5678'.split(','); // => ['1234', '5678'];
Then parse each element of the array to convert them to numbers and then you can sum them.
Here's how I'd do it:
var nums = "1,2,3,4,5";
var sum = nums.split(',').reduce(function(memo, num) {
return memo + parseInt(num, 10);
}, 0);
console.log(sum); // => 15
That should work. See jsbin example.
Note the split parameter needs to match the delimiters you use in your string. for this example ',' is appropriate. For your example you might need /\s*,\s*/.
Unrelated
Since you provided an example of code I can see that you're spending a lot of effort attempting to duck punch and transform the values to the types you need instead of exposing the types in an object. Might I suggest:
function Stack(cards) {
this.cards = cards || [];
}
Stack.prototype.toString = function() {
return this.cards.join(' , ');
};
Stack.prototype.sum = function() {
return this.cards.reduce(function(memo, card) {
return memo + parseInt(card, 10);
}, 0);
};
function randomCard() {
return Math.floor(Math.random() * 13) + 1;
}
Stack.dealHand = function() {
var card1 = randomCard(), card2;
do { card2 = randomCard(); } while (card1 === card2);
return new Stack([card1, card2]);
};
// Example
var hand = Stack.dealHand();
console.log(hand + ' = ' + hand.sum()); // => '3 , 11 = 14'

How to pick a random number in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: Getting random value from an array
I have a list of ten items.
ar = [112,32,56,234,67,23,231,123,12]
How do I choose an item randomly with javascript?
var ar = [112,32,56,234,67,23,231,123,12];
var randomKey = Math.floor(Math.random() * ar.length);
var randomValue = ar[randomKey];
Check out the documentation on the Math object; https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math
You could easily abstract this into a nice function:
function getRandom(array, getVal) {
var key = Math.floor(Math.random() * array.length);
if (getVal) {
return array[key];
}
return key;
}
Then you'd call it like getRandom(ar) to get a random key in the array, and getRandom(ar, true) to return a random value in the array.
well something like
var randnum = Math.floor ( Math.random() * ar.length );
val random = (ar[randnum]);

Categories

Resources