Languages
[Edit]
EN

JavaScript - round with precision up-to n decimal places

2 points
Created by:
Root-ssh
177980

In this article, we would like to show you how to round up numbers with precision in JavaScript.

Custom method example

// ONLINE-RUNNER:browser;

function ceilPrecised(number, precision) {
	var power = Math.pow(10, precision);

  	return Math.ceil(number * power) / power;
}

// Examples:

console.log( ceilPrecised(     5  ,  0 ) ); // 5
console.log( ceilPrecised(     5. ,  0 ) ); // 5
console.log( ceilPrecised(      .5,  0 ) ); // 1

console.log( ceilPrecised(  1.1234,  0 ) ); // 2
console.log( ceilPrecised(  1.1234,  1 ) ); // 1.2
console.log( ceilPrecised(  1.1235,  2 ) ); // 1.13
console.log( ceilPrecised(  1.1235,  3 ) ); // 1.124

console.log( ceilPrecised( -1.1234,  0 ) ); // -1
console.log( ceilPrecised( -1.1234,  1 ) ); // -1.1
console.log( ceilPrecised( -1.1234,  2 ) ); // -1.12
console.log( ceilPrecised( -1.1234,  3 ) ); // -1.123
 
console.log( ceilPrecised(    1234, -1 ) ); // 1240
console.log( ceilPrecised(    1234, -2 ) ); // 1300
console.log( ceilPrecised(    1234, -3 ) ); // 2000

console.log( ceilPrecised(  5_000.000_001,  0 ) ); // 5001
console.log( ceilPrecised(  5_000.000_001,  6 ) ); // 5000.000001
console.log( ceilPrecised(  5_000.000_001, -3 ) ); // 6000

See also

  1. JavaScript - Math.ceil() method example

Alternative titles

  1. JavaScript - how to round ceil with precision up-to n decimal places example
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.

JavaScript - math (popular problems)

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