1//There are meny ways of rounding...
2Math.floor(5.5) //Answer 5, it alwas rounds down.
3Math.round(5.5) //Answer 6, it simpily rounds to the closest whole number.
4Math.ceil(5.5) //Answer 6, it alwas rounds up.
5
6//You can do more things too...
7Math.floor(5.57 * 10) / 10 //Answer 5.5, the number turns into 55.7, Then gets floored (55.0), Then gets divied, (5.5).
1function round(num, places) {
2 num = parseFloat(num);
3 places = (places ? parseInt(places, 10) : 0)
4 if (places > 0) {
5 let length = places;
6 places = "1";
7 for (let i = 0; i < length; i++) {
8 places += "0";
9 places = parseInt(places, 10);
10 }
11 } else {
12 places = 1;
13 }
14 return Math.round((num + Number.EPSILON) * (1 * places)) / (1 * places)
15}
16
17round(1.005, 2); // 1.01
18round(1.005, "1"); // 1
19round("1.23", 1); // 1.2
20round("1.436", "2"); // 1.44
1// rounds the result to the closest integer
2//syntax Math.round(x);
3
4console.log(Math.round(0.9));
5// expected output: 1
6
7console.log(Math.round(5.95), Math.round(5.5), Math.round(5.05));
8// expected output: 6 6 5
9
10console.log(Math.round(-5.05), Math.round(-5.5), Math.round(-5.95));
11// expected output: -5 -5 -6