<!DOCTYPE html>
<
html
>
<
head
>
<
title
>
Gaussian/banker's rounding in JavaScript
</
title
>
</
head
>
<
body
style
=
"text-align:center;"
>
<
h1
style
=
"color:green;"
>
GeeksforGeeks
</
h1
>
<
p
id
=
"GFG_UP"
style="font-size: 20px;
font-weight: bold">
</
p
>
Type Here:
<
input
id
=
"inp"
/>
<
br
>
<
br
>
<
button
id
=
"button"
onclick
=
"GFG_Fun();"
>
click here
</
button
>
<
p
id
=
"GFG_DOWN"
style="font-size: 26px;
font-weight: bold;
color: green;">
</
p
>
<
script
>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML =
"Type number and click on the button to round the number"
+" in the Gaussian/banker's format.";
function roundIt(n, d = 0) {
var m = Math.pow(10, d);
var n = +(d ? n * m : n).toFixed(8);
var i = Math.floor(n),
diff = n - i; // getting the difference
var e = 1e-8; // Rounding errors in var(diff)
// Checking if the difference is less than or
// greater than, based on that adding the 1 to it.
var r = (diff > 0.5 - e && diff <
0.5
+ e) ?
((i % 2 == 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r; // if d != 0 then returning r/m else r
}
function GFG_Fun() {
var
inp
=
Number
(document.getElementById('inp').value);
down.innerHTML
=
roundIt
(inp);
}
</script>
</
body
>
</
html
>