How can I use Math.random() to generate a number only to the tenths place?

Viewed 305

class AlienShip {
    constructor() {
        //random number between 3 and 6
        this.hull = Math.floor(Math.random() * 4) + 3;
        //random number between 2 and 4
        this.firePower = Math.floor(Math.random() * 3) + 2;
        //random number between .6 and .8
        this.accuracy = Math.floor(Math.random() * 1.2) + .6;
    }
}

I'm trying to get a random number between .6 and .8 that is rounded to the tenths.

2 Answers

You could take a factor and an adjustment, at the end divide by ten.

console.log(Math.floor(Math.random() * 3 + 6) / 10)

This will make min included and max included

(Math.random() * (max - min + 1)) + min

(Math.random() *(8-6+1) +6)/10

0.6 to 0.9

0.67.., 0.83.. but never above or 0.9...



This will make min included and max excluded

(Math.random() * (max - min)) + min

(Math.random() *(8-6) +6)/10

0.67.., 0.79.. but never above or 0.8...

Related