1. 程式人生 > >JavaScript Math物件 ceil()、floor()、round()方法

JavaScript Math物件 ceil()、floor()、round()方法

Math.ceil()
功能:
對一個數進行上取整。 語法:Math.ceil(x) 引數:
  • x:一個數值。
返回值:返回大於或等於x,並且與之最接近的整數。 注:如果x是正數,則把小數;如果x是負數,則把小數 例: <script type="text/javascript">
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

Math.floor()

功能:對一個數進行下取整。 語法:Math.floor(x) 引數:
  • x:一個數值。
返回值:返回小於或等於x,並且與之最接近的整數。 注:如果x是正數,則把小數;如果x是負數,則把小數 例: <script type="text/javascript">
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) 引數:
  • x:一個數值。
返回值:x最接近的整數。 例: <script type="text/javascript">
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

應用例項,自己做的標的詳情頁面有個滿標時間倒計時器,具體程式碼如下,僅供參考

<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>