generatng a random decimal value

megan1989

Baseband Member
Messages
29
Location
USA
I know that when you use the math.random() that it generates a random value with many places : 5.6938506849, and I need it to just generate two decimal value: 5.69. How do I do this, here is a portion of the code:

//problem 1
var num1a = (Math.random()* 10) + 1;
var num1b = (Math.random()* 10) + 1;
var product1 = num1a * num1b;
var response = parseFloat(prompt("What is the product of " + num1a + " and " + num1b + " ?"));
if (response == product1)
{
count1 = count1 + 1;
result = "correct!";
alert(result);
}
else
{
result = "incorrect";
alert(result);
}
if (count1 == 3)
{
levelTwo();
return;
}

Thank you!
 

Draygoes

Fully Optimized
Messages
1,655
Location
United States
Wrap your Math.Random functions in Math.Floor()...

I have altered your script to reflect this:

//problem 1
var num1a = Math.floor((Math.random() * 10) + 1);
var num1b = Math.floor((Math.random() * 10) + 1);
var product1 = num1a * num1b;
var response = parseFloat(prompt("What is the product of " + num1a + " and " + num1b + " ?"));
if (response == product1)
{
count1 = count1 + 1;
result = "correct!";
alert(result);
}
else
{
result = "incorrect";
alert(result);
}
if (count1 == 3)
{
levelTwo();
return;
}

It will return a single digit value, without the need for decimals at all.
 
Last edited:
Top