JavaScript Math物件 ceil()、floor()、round()方法
阿新 • • 發佈:2019-01-10
Math.ceil()
功能:對一個數進行上取整。 語法:Math.ceil(x) 引數:
document.write( Math.ceil(1.2)+", "+Math.ceil(1.8)+", "+Math.ceil(-1.2)+", "+Math.ceil(-1.8) );
</script> 輸出結果為: document.write( Math.ceil(1.2)+", "+Math.ceil(1.8)+", "+Math.ceil(-1.2)+", "+Math.ceil(-1.8) ); 2, 2, -1, -1
document.write( Math.floor(1.2)+", "+Math.floor(1.8)+", "+Math.floor(-1.2)+", "+Math.floor(-1.8) );
</script> 輸出結果為: document.write( Math.floor(1.2)+", "+Math.floor(1.8)+", "+Math.floor(-1.2)+", "+Math.floor(-1.8) ); 1, 1, -2, -2
Math.round()
功能:四捨五入取整。
語法:Math.round(x)
引數:
document.write( Math.round(1.2)+", "+Math.round(1.8)+", "+Math.round(-1.2)+", "+Math.round(-1.8) );
</script> 輸出結果為: document.write( Math.round(1.2)+", "+Math.round(1.8)+", "+Math.round(-1.2)+", "+Math.round(-1.8) ); 1, 2, -1, -2
功能:對一個數進行上取整。 語法:Math.ceil(x) 引數:
- x:一個數值。
document.write( Math.ceil(1.2)+", "+Math.ceil(1.8)+", "+Math.ceil(-1.2)+", "+Math.ceil(-1.8) );
</script> 輸出結果為: document.write( Math.ceil(1.2)+", "+Math.ceil(1.8)+", "+Math.ceil(-1.2)+", "+Math.ceil(-1.8) );
Math.floor()
功能:對一個數進行下取整。 語法:Math.floor(x) 引數:- x:一個數值。
document.write( Math.floor(1.2)+", "+Math.floor(1.8)+", "+Math.floor(-1.2)+", "+Math.floor(-1.8) );
</script> 輸出結果為: document.write( Math.floor(1.2)+", "+Math.floor(1.8)+", "+Math.floor(-1.2)+", "+Math.floor(-1.8) );
- x:一個數值。
document.write( Math.round(1.2)+", "+Math.round(1.8)+", "+Math.round(-1.2)+", "+Math.round(-1.8) );
</script> 輸出結果為: document.write( Math.round(1.2)+", "+Math.round(1.8)+", "+Math.round(-1.2)+", "+Math.round(-1.8) );
應用例項,自己做的標的詳情頁面有個滿標時間倒計時器,具體程式碼如下,僅供參考
<script type="text/javascript">
$(function() {
setTimeout('showTime()', 1000);
});
function showTime() {
var endTime = $("#endTime").val();//滿標時間
time_end = new Date(endTime);//結束的時間
var tt = time_end.getTime();
var now = new Date().getTime();
var cha = tt - now;
var SysSecond = parseInt(cha);
if (SysSecond > 0) {
int_day = Math.floor(SysSecond / 86400000);
SysSecond -= int_day * 86400000;
int_hour = Math.floor(SysSecond / 3600000);
SysSecond -= int_hour * 3600000;
int_minute = Math.floor(SysSecond / 60000);
SysSecond -= int_minute * 60000;
int_second = Math.floor(SysSecond / 1000);
if (int_hour < 10) {
int_hour = "0" + int_hour;
}
if (int_minute < 10) {
int_minute = "0" + int_minute;
}
if (int_second < 10) {
int_second = "0" + int_second;
}
$("#day").html(int_day);
$("#hours").html(int_hour);
$("#minutes").html(int_minute);
$("#seconds").html(int_second);
} else {
$("#day").html("00");
$("#hours").html("00");
$("#minutes").html("00");
$("#seconds").html("00");
}
setTimeout('showTime()', 1000);
}
</script>