Languages
[Edit]
EN

JavaScript / VanillaJS - write own round function implementation

12 points
Created by:
p_agon
589

In this article, we would like to show you how to write your own round function in JavaScript.

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);
  	}
}


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

See also

  1. JavaScript - Math.round() method example

Alternative titles

  1. JavaScript / VanillaJS - how to write own round function implementation?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join