EN
TypeScript - round with precision down-to n decimal places
0 points
In this article, we would like to show you how to round with precision down-to n decimal places in TypeScript.
In this example, we create a custom function that uses Math.pow()
and Math.floor()
methods to round with precision down-to n decimal places.
xxxxxxxxxx
1
function floorPrecised(number: number, precision: number): number {
2
var power = Math.pow(10, precision);
3
4
return Math.floor(number * power) / power;
5
}
6
7
// Examples:
8
console.log( floorPrecised( 1.1234, 0 ) ); // 1
9
console.log( floorPrecised( 1.1234, 1 ) ); // 1.1
10
console.log( floorPrecised( 1.1235, 2 ) ); // 1.12
11
console.log( floorPrecised( 1.1235, 3 ) ); // 1.123
12
13
console.log( floorPrecised( -1.1234, 0 ) ); // -2
14
console.log( floorPrecised( -1.1234, 1 ) ); // -1.2
15
console.log( floorPrecised( -1.1234, 2 ) ); // -1.13
16
console.log( floorPrecised( -1.1234, 3 ) ); // -1.124
17
18
console.log( floorPrecised( 1234, -1 ) ); // 1230
19
console.log( floorPrecised( 1234, -2 ) ); // 1200
20
console.log( floorPrecised( 1234, -3 ) ); // 1000
21
22
console.log( floorPrecised( 5 , 0 ) ); // 5
23
console.log( floorPrecised( 5. , 0 ) ); // 5
24
console.log( floorPrecised( .5, 0 ) ); // 0
25
26
console.log( floorPrecised( 5_000.000_001, 0 ) ); // 5000
27
console.log( floorPrecised( 5_000.000_001, 6 ) ); // 5000.000001
28
console.log( floorPrecised( 5_000.000_001, -3 ) ); // 5000
Output:
xxxxxxxxxx
1
1
2
1.1
3
1.12
4
1.123
5
6
-2
7
-1.2
8
-1.13
9
-1.124
10
11
1230
12
1200
13
1000
14
15
5
16
5
17
0
18
19
5000
20
5000.000001
21
5000