JavaScript represents a foundational scripting language for the web. Within JavaScript, web programmers find a fully functional object-oriented scripting language with numerous built-in capabilities. Many of these capabilities come from the "Math" object and the computations it allows programmers to perform. Through the Math object, programmers can round numbers traditionally, or use the "floor()" and "ceil()" functions to perform more specialized rounding operations. Through these functions, the programmer can also round or truncate decimals to an arbitrary precision.
Rounding in JavaScript
JavaScript uses the "round()" function, packaged as part of the "math" object, to round decimal fractions to the nearest integer. This operation will always return an integer, with no decimal parts. In order to round to a specific decimal, the programmer can include the round() function in the following equation, where n = the number to round and t the number of decimal places to round to:
(round(n * 10^t)) / 10^t
For example, to round the number 4.543 to two decimal places, the JavaScript command would look like this:
(Math.round(n*100) / 100
Rounding Using the "floor()" and "ceil()" Functions
Another way to round in JavaScript involves two other Math object functions, the "floor()" and "ceil()" (ceiling) functions. The ceil() function rounds to the nearest integer towards positive infinity, regardless of the decimal part. So, 3.1 will round toward 4, and -3.9 will round to 3. The floor() function rounds to the nearest integer towards negative infinity. So, 3.9 will round to 3, and -3.1 will round to -4.
Truncating
"Truncating" a number means dropping the fractional part of a decimal number. A truncation operation does not round a number; it simply drops the fractional portion of the
float x = 4.5634;
int y = (int)x; //y = 4
Truncating in JavaScript 0){
n = Math.floor(n);
}
else if (n < 0){
n = Math.ceil(n);
}