Wednesday 27 February 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...