Wednesday, February 27, 2019

javascript - Set a minimum value for randomly generated numbers




I am using this function to generate and alternate random values inside a div






var change_price = $('#myprice');
animationTimer = setInterval(function() {
change_price.text( ''+ Math.floor(Math.random() * 100) );
}, 1000);

#myprice {
padding: 20px;
font-size:24px;
color: green;
}



50





What I want to do is to control the min value too.
For example, to have random generated values from 50 to 100.
Not starting from zero(0) as other posts do


Answer



As mentioned in mozilla developer you can generate random number between max and min as shown in bottom




Math.floor(Math.random() * (max - min + 1)) + min;


So your code should changed to





var change_price = $('#myprice');
animationTimer = setInterval(function() {

change_price.text(Math.floor(Math.random() * (100-50+1)) + 50);
}, 100);

#myprice {
padding: 20px;
font-size:24px;
color: green;
}


50





No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...