8
Rounding Numbers
2021-02-03 - JavaScript
1// JS Tip of the Day
2// Rounding Numbers
3
4const myNumber = 3.14159;
5
6// Rounding Nearest
7console.log('Math.round', Math.round(myNumber)); // 3
8
9// Rounding Up
10console.log('Math.ceil', Math.ceil(myNumber)); // 4
11
12// Rounding Down
13console.log('Math.floor', +Math.floor(myNumber)); // 3
14
15// Rounding to a specified number of decimals - 2nd digit example
16// multiply and divide by 100 or a bigger power of 10 for more digits
17console.log('Math.ceil', Math.ceil(myNumber)); // 3.14
18
19// Rounding to a specified number of decimals - 2nd digit example
20// toFixed return a string and we have to convert it to a number
21console.log('Number.toFixed', +myNumber.toFixed(2)); // 3.14
22
23// Removing anything after the decimal point - ES6/ES2015
24console.log('Math.trunc', Math.trunc(myNumber)); // 3
#JStipoftheday