So I use such script for random int generation inside of range
function randomInRange(start, end)
{
if ((start >= 0) && (end >= 0))
{
return Math.round(Math.abs(start) + (Math.random() * (Math.abs(end) - Math.abs(start))));
}
else if ((start <= 0) && (end <= 0))
{
return 0 - (Math.round(Math.abs(start) + (Math.random() * (Math.abs(end) - Math.abs(start)))));
}
else
{
return Math.round(((start) + Math.random() * (end - start)));
}
}
You can see it at work here. for Positive ranges its correct, for negative its correct but I get bad and wrong results for mixed. Why and how to fix it?
I try to use formula like Math.round(start + Math.random() * (end - start));
OK, I found the problem, you’re performing algebra on strings (since in your code
$('fnt').valueis the value of an input box, which is a string), not numbers, so things like+will end up concatenating strings and not adding their numeric content. In your particular example, you have:Which evaluates to:
Which evaluates to (for example):
Since
'13' + '-339.44615370430984'will be concatenated, and finally theMath.roundcall will returnNaNYou should have:
Or change the values you pass into the function, making sure they’re numbers.