Top community members

If you think it is valuable to share IT knowledge and help others.

It is the right place for you. ❀ đŸ’»

Join our community.

[Edit]
EN

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

12 points
Created by:
AnnLen
1662

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more