1 // value is the value to round
2 // places if positive the number of decimal places to round to
3 // places if negative the number of digits to round to
4 function roundTo(value, places){
5 var power = Math.pow(10, places);
6 return Math.round(value * power) / power;
7 }
8 var myNum = 10000/3; // 3333.3333333333335
9 roundTo(myNum, 2); // 3333.33
10 roundTo(myNum, 0); // 3333
11 roundTo(myNum, -2); // 3300
12
1 function ceilTo(value, places){
2 var power = Math.pow(10, places);
3 return Math.ceil(value * power) / power;
4 }
5 function floorTo(value, places){
6 var power = Math.pow(10, places);
7 return Math.floor(value * power) / power;
8 }
9
1 var myNum = 2/3; // 0.6666666666666666
2 var multiplier = 100;
3 var a = Math.round(myNum * multiplier) / multiplier; // 0.67
4 var b = Math.ceil (myNum * multiplier) / multiplier; // 0.67
5 var c = Math.floor(myNum * multiplier) / multiplier; // 0.66
6
1 var myNum = 10000/3; // 3333.3333333333335
2 var multiplier = 1/100;
3 var a = Math.round(myNum * multiplier) / multiplier; // 3300
4 var b = Math.ceil (myNum * multiplier) / multiplier; // 3400
5 var c = Math.floor(myNum * multiplier) / multiplier; // 3300
6
1Math.trunc(2.3); // 2 (floor)
2Math.trunc(-2.3); // -2 (ceil)
3Math.trunc(2147483648.1); // 2147483648 (floor)
4Math.trunc(-2147483649.1); // -2147483649 (ceil)
5Math.trunc(NaN); // NaN
6
1var c = Math.round(-2.7); // c is now -3
2var c = Math.round(-2.5); // c is now -2
3
1var a = Math.ceil(2.3); // a is now 3
2var b = Math.ceil(2.7); // b is now 3
3