Difference between Math.floor() and Math.round()
by nirmaljpatel
HTML
<h1>Enter the Left Hand Side text box value to get Result on Right hand side text box.</h1>
<div id="floorDiv">Result of Math.floor(
<input type="text" id="floor" onkeyup="forFloor()" value="2.6"> ) is
<input type="text" id="floorOut" readonly>.
</div>
<div id="roundDiv">Result of Math.round(
<input tyep="text" id="round" onkeyup="forRound()" value="2.6"> ) is
<input type="text" id="roundOut" readonly>.
</div>
CSS
div {
margin-top:1.2em;
font-size:1.5em;
}
input{
width:60px;
height:25px;
padding-left:10px;
font-weight:bold;
color:red;
}
JavaScript
function forFloor() {
document.getElementById('floorOut').value = Math.floor(document.getElementById('floor').value);
}
function forRound() {
document.getElementById('roundOut').value = Math.round(document.getElementById('round').value);
}
$(document).ready(function() {
$("#floor, #round").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
forRound();
forFloor();
});