js获得给定区间[m,n]的随机数

xiaoxiao2021-02-27  150

获得给定区间[m,n]的随机数 第一种方法

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

第二种方法

function getRandomInt(min,max){ min = Math.ceil(min); max = Math.round(max); return Math.floor(Math.random()*(max-min)+min); }

可以通过round()、ceil()、floor()方法,去掉小数

Math.round();//向下取整 Math.floor();//向下取整 Math.ceil();//向上取整 Math.round(3.535);//3 Math.floor(3.535);//3 Math.ceil(3.535);//4

通过toFixed(n)方法,确定保留n位小数

3.535.toFixed(2);//3.54
转载请注明原文地址: https://www.6miu.com/read-17266.html

最新回复(0)