Languages
[Edit]
EN

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

12 points
Created by:
AnnLen
12070

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