# Math.random()

## 語法

```Math.random()
```

## 範例

### Getting a random number between 0 (inclusive) and 1 (exclusive)

js
``````function getRandom() {
return Math.random();
}
``````

### Getting a random number between two values

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) `min`, and is less than (and not equal) `max`.

js
``````function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
``````

### Getting a random integer between two values

This example returns a random integer between the specified values. The value is no lower than `min` (or the next integer greater than `min` if `min` isn't an integer), and is less than (but not equal to) `max`.

js
``````function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
``````

### Getting a random integer between two values, inclusive

While the `getRandomInt()` function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The `getRandomIntInclusive()` function below accomplishes that.

js
``````function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive
}
``````

## 規範

Specification
ECMAScript Language Specification
# sec-math.random

## 瀏覽器相容性

BCD tables only load in the browser