Page 73 - JavaScript
P. 73
NaN | 0; // 0
6
Math.trunc()
Math.trunc(2.3); // 2 (floor)
Math.trunc(-2.3); // -2 (ceil)
Math.trunc(2147483648.1); // 2147483648 (floor)
Math.trunc(-2147483649.1); // -2147483649 (ceil)
Math.trunc(NaN); // NaN
Rounding to decimal places
Math.floor, Math.ceil(), and Math.round() can be used to round to a number of decimal places
To round to 2 decimal places:
var myNum = 2/3; // 0.6666666666666666
var multiplier = 100;
var a = Math.round(myNum * multiplier) / multiplier; // 0.67
var b = Math.ceil (myNum * multiplier) / multiplier; // 0.67
var c = Math.floor(myNum * multiplier) / multiplier; // 0.66
You can also round to a number of digits:
var myNum = 10000/3; // 3333.3333333333335
var multiplier = 1/100;
var a = Math.round(myNum * multiplier) / multiplier; // 3300
var b = Math.ceil (myNum * multiplier) / multiplier; // 3400
var c = Math.floor(myNum * multiplier) / multiplier; // 3300
As a more usable function:
// value is the value to round
// places if positive the number of decimal places to round to
// places if negative the number of digits to round to
function roundTo(value, places){
var power = Math.pow(10, places);
return Math.round(value * power) / power;
}
var myNum = 10000/3; // 3333.3333333333335
roundTo(myNum, 2); // 3333.33
roundTo(myNum, 0); // 3333
roundTo(myNum, -2); // 3300
And the variants for ceil and floor:
function ceilTo(value, places){
var power = Math.pow(10, places);
return Math.ceil(value * power) / power;
}
function floorTo(value, places){
https://riptutorial.com/ 30

