Math.floor(Math.random() * 100) + 1 + '%'
Math.random() applied as a percentage?
-
04-07-2023 - |
Question
so I have this code that is giving me a random number for both top and left attribute of some images.
var random1 = Math.ceil(Math.random() * 500);
var random2 = Math.ceil(Math.random() * 500);
$(document).ready(function () {
$('#randomp').css('top', random1);
$('#randomp').css('left', random2);
});
The problem is that I would be prefer to randomize a number between 1 and 100%. Is that possible?
La solution
Autres conseils
Since Math.random returns number that is random, not less than 0
and less than 1
, you have just to multiply result by 99
instead of 500
to get a number beetween 1
and 100
%.
Finally, the code should be as follows:
var random1 = Math.round(Math.random() * 99) + 1;
var random2 = Math.round(Math.random() * 99) + 1;
This gives you a number between 0 and 100 (both included):
Math.floor(Math.random() * 101);
- Math random will give you a number between 0 (included) and 1 (excluded)
- If you multiply that number with 101, it will give you a number between 0 (included) and 101 (excluded)
- Math.floor will return the the largest integer less than or equal to the above number.
Not sure if you want it rounded or not, so here's both:
console.log( rando(1, 100) + "%" );
console.log( rando(1, 100, "float") + "%" );
<script src="https://randojs.com/1.0.0.js"></script>
This uses randojs.com to make the randomness simple and readable. If you need to know more, check out the website.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow