This content has been marked as final. Show 5 replies
Generate a full number that has as many digits as the float number you want, then divide by 10^the number of decimal parts.
E.g., if your number consists of 3 full numbers and 2 decimals, like 123.45, generate a 5-digit number (12345), then divide by 100 (10^2), to get 123.45.
That's also the way to round numbers to a certain accuracy: for 2 decimal parts, multiply by 100, round it and divide by 100.
well atm im using this code:
return Math.floor(Math.random() * 2);
so instead of the *2 should i have return Math.floor(Math.random() * 100)/100;
I can't see where you're going with that code... it shuffles an array of full numbers and gets one of them. If you want decimal numbers you could just fill the array with decimals instead of full numbers. Changing the shuffle method wouldn't change the numbers in the array, just the way of sorting it.
If you want just one random number, you don't need the array at all, but you could use something like this:
Math.round( (10 + Math.random() * 10) * 100 ) / 100;
for a random number with 2 decimal parts between 10 and 20.
ok sorry, im more a designer than programmer, so im learning Actionscripting as i need it.
so if i had
display = Math.round( (10 + Math.random() * 10) * 100 ) / 100;
where "display" is the var name of a text box this would work?
so is this right, basically (10 + Math.random() is telling the random number to be 2 digits long? sorry then i get lost
If 'display' is the variable bound to a textbox, it's ok. If it's the instance name (like in the 1st posting), it should be display.text.
The expression works like this:
Math.random() gets a number like 0.123456789.
To have 2 decimal parts, move the dot (.) 2 digits to the right. This is done by multiplying with 100. Now it's 12.3456789.
Now Math.round() this, and we have 12.
Last step is moving the dot 2 digits to the left again, which means divide by 100, and we then have 0.12. In short:
Math.round( Math.random()*100 ) / 100
That's the way to round numbers to a certain accuracy. For 3 decimal parts, use 1000 instead of 100, and so on.
The part (10 + Math.random() * 10) is there to get numbers between 10 and 20: Math.random() is always between 0 and 1, so by multiplying this with 10, we get numbers between 0 and 10. As the lowest number should be 10, we must add 10 to this, so that the result is between 10 and 20.
It's a bit complicated on the first look, but if you think it through it's all quite logical.