Languages
[Edit]
EN

JavaScript - how to round with precision down-to n decimal places example

6 points
Created by:
Marcin
2477

In JavaScript it is possible to round down numbers with precision in following way.

1. Custom method example

// ONLINE-RUNNER:browser;

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

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

// Examples:
console.log( floorPrecised(  1.1234,  0 ) ); // 1
console.log( floorPrecised(  1.1234,  1 ) ); // 1.1
console.log( floorPrecised(  1.1235,  2 ) ); // 1.12
console.log( floorPrecised(  1.1235,  3 ) ); // 1.123

console.log( floorPrecised( -1.1234,  0 ) ); // -2
console.log( floorPrecised( -1.1234,  1 ) ); // -1.2
console.log( floorPrecised( -1.1234,  2 ) ); // -1.13
console.log( floorPrecised( -1.1234,  3 ) ); // -1.124
 
console.log( floorPrecised(    1234, -1 ) ); // 1230
console.log( floorPrecised(    1234, -2 ) ); // 1200
console.log( floorPrecised(    1234, -3 ) ); // 1000

console.log( floorPrecised(     5  ,  0 ) ); // 5
console.log( floorPrecised(     5. ,  0 ) ); // 5
console.log( floorPrecised(      .5,  0 ) ); // 0

console.log( floorPrecised(  5_000.000_001,  0 ) ); // 5000
console.log( floorPrecised(  5_000.000_001,  6 ) ); // 5000.000001
console.log( floorPrecised(  5_000.000_001, -3 ) ); // 5000

See also

  1. JavaScript - Math.ceil() method example
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists 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.