0

I'm using this code to get a random number in the range of min-max. for some reason, I get numbers that are bigger than max. (the console.log shows that the min and max are set correctly.) (I'm showing here the relevant code. this is not the whole file.)

const RandomNumber = () => {
    const [min, setMin] = useState(0)
    const [max, setMax] = useState(0)
    const [rand, setRand] = useState(0)
    const classes = useStyles();
  
    const setRandom = () => {
        console.log(min);
        console.log(max);
        let random = (Math.floor(Math.random() * (max - min + 1)) + min)
        console.log(random);
        setRand(random)
    }

    return (
        <>
            <Stack direction="row" spacing={2} className={classes.root}>
                <TextField
                    id="filled-number"
                    label="Min-Number"
                    type="number"
                    InputLabelProps={{
                        shrink: true,
                    }}
                    variant="filled"
                    onChange={(e) => setMin(e.target.value)}
                />
                <TextField
                    id="filled-number"
                    label="Max-Number"
                    type="number"
                    InputLabelProps={{
                        shrink: true,
                    }}
                    variant="filled"
                    onChange={(e) => setMax(e.target.value)}
                />
                <Stack spacing={2} direction="row">
                    <Button variant="outlined" className={classes.button} onClick={setRandom}>Get Random!</Button>
                </Stack>

            </Stack>
            <h1>rand is: {rand}</h1>
        </>
    );
}

export default RandomNumber;
Yuda
  • 69
  • 7

2 Answers2

2

I think you need to convert your e.target.value in setMax and setMin to number

e.target.value && !isNaN(e.target.value) && setMax(Number(e.target.value))

Similar for setMin

e.target.value && !isNaN(e.target.value) && setMin(Number(e.target.value))
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
2

It is because e.target.value is a string type, so the problem is on this line of code.

let random = (Math.floor(Math.random() * (max - min + 1)) + min)

Say for example max = "25" and min="9" (this is string because you set from e.target.value without casting it to int,

"25" - "9" = 14 works fine, but

Math.floor(....) + min

int + string = string

So say for example Math.floor result is 12,

12 + "9" = "129"

David Yappeter
  • 1,434
  • 3
  • 15