第一種:四舍五入
function fixed2(num){
num = num.toFixed(2);
}
例子:
var num =? 1.345465765柔吼;
num = num.toFixed();
console.log(num)羽氮;
說(shuō)明:toFixed(),括號(hào)里是就保留幾位小數(shù)//強(qiáng)制保留兩位小數(shù)? num=1.23635435? fixed2(num)=1.24? num=1.2? ? fixed2(num)=1.20
第二種://向下取整
Math.floor();?
第三種:四舍五入
function toDecimal(x) {
? ? ? ? ? var f = parseFloat(x);
? ? ? ? ? if (isNaN(f)) {
? ? ? ? ? ? return;
? ? ? ? ? }
? ? ? ? ? f = Math.round(x*100)/100;
? ? ? ? ? return f;
}
函數(shù)名用法說(shuō)明
floor向下取整Math.floor()Math.floor(11.46)=Math.floor(11.68)=Math.floor(11.5)=12
Math.floor(-11.46)=Math.floor(-11.68)=Math.floor(-11.5)=-11
ceil向上取整Math.ceil()Math.ceil(11.46)=Math.ceil(11.68)=Math.ceil(11.5)=12
Math.ceil(-11.46)=Math.ceil(-11.68)=Math.ceil(-11.5)=-11
round四舍五入Math.round()小數(shù)點(diǎn)后第一位<5
正數(shù):Math.round(11.46)=11
負(fù)數(shù):Math.round(-11.46)=-11
小數(shù)點(diǎn)后第一位>5
正數(shù):Math.round(11.68)=12
負(fù)數(shù):Math.round(-11.68)=-12
random? 隨機(jī)數(shù)Math.random()介于0~1之間的隨機(jī)數(shù)