Languages
[Edit]
EN

JavaScript / VanillaJS - how to write own round function implementation?

12 points
Created by:
AnnLen
1876

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

See also

  1. JavaScript - Math.round() method example
Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.