EN
JavaScript / VanillaJS - how to write own round function implementation?
12
points
In JavaScript it is possible to write own round function in following way.
1. Custom round method examples
// ONLINE-RUNNER:browser;
function roundNumber(value) {
if (value < 0.0) {
var rest = (value % 1.0);
if(rest < -0.5) {
rest += 1.0;
}
return value - rest;
} else {
value += 0.5;
return value - (value % 1.0);
}
}
// Example:
console.log( roundNumber( 5 ) ); // 5
console.log( roundNumber( 2.49 ) ); // 2
console.log( roundNumber( 2.50 ) ); // 3
console.log( roundNumber( 2.51 ) ); // 3
console.log( roundNumber( 0.999 ) ); // 1
console.log( roundNumber( 1.001 ) ); // 1
console.log( roundNumber( -2.49 ) ); // -2
console.log( roundNumber( -2.50 ) ); // -2
console.log( roundNumber( -2.51 ) ); // -3
console.log( roundNumber( -1.001 ) ); // -1