怎样对小数进行向上取整 / 向下取整 / 四舍五入 / 保留n位小数 / 生成随机数

时间:2021-12-08 08:17:26

1. 向上取整使用: Math.ceil()

Math.ceil(0.1); //
Math.ceil(1.9); //

2. 向下取整使用: Math.floor()

Math.floor(0.1); //
Math.floor(1.9); //

3. 四舍五入取整使用: Math.round()

Math.round(0.1); //
Math.round(1.9); //

4. 保留n位小数使用: Number().toFixed(n)

Number(2.134).toFixed(2); // 2.13
Number(2.135).toFixed(2); // 2.13
Number(2.136).toFixed(2); // 2.14

5. 生成区间随机数使用Math.random();

// 方法1
parseInt(Math.random()*(max-min+1)+min,10); // 方法2
Math.floor(Math.random()*(max-min+1)+min);