# Javascript ceil, floor and toFixed take the largest and smallest integer and round specified decimal

Lionsure 2020-06-15 Original by the website

Javascript as a scripting language is still somewhat different from the C family languages. In terms of taking integers, the C family languages can use slash operation to get the numbers, but the slash operation in javascript will retain the decimal number. Two functions are needed to achieve the same effect as the C family languages, namely Math.ceil() and Math.floor(), which takes the largest and smallest integer.

Javascript takes the decimal and uses the toFixed() method, just round a few decimals and enter a few in the parentheses. The following uses examples to introduce to take integers (i.e. take the largest and smallest integer) and take the decimal in javascript.

### I. Takes the largest and smallest integer with math floor and math ceil in javascript

There are two functions for taking integers in javascript, namely Math.ceil() and Math.floor(), which are not rounded off; if you take the largest integer, as long as it is not 0 after the decimal point, it will carry 1 forward; if you take the smallest integer, No matter whether it is greater than or equal to 5 after the decimal point, it is discarded, which is the same as the slash operation in C#.

1. Takes the largest integer with javascript ceil

Use the Math.ceil() method to get the largest integer, for example:

var a = Math.ceil(3.0), b = Math.ceil(3.1), c = Math.ceil(3.5);
alert("a=" + a + "; b=" + b + "; c=" + c);

Output: a=3; b=4; c=4

As can be seen from the output, as long as the number behind decimal point is not 0, when you use the Math.ceil() method, it will automatically advance by 1 forward, and the 3.1 will also change to 4.

2. Takes the smallest integer with javascript floor

You can use the Math.floor() method to get the smallest integer, for example:

var a = Math.floor(3.0), b = Math.floor(3.1), c = Math.floor(3.5), d = Math.floor(3.8);
alert("a=" + a + "; b=" + b + "; c=" + c + "; d=" + d);

Output: a=3; b=3; c=3; d=3

It can be seen from the output that regardless of whether the number behind decimal point is greater than or equal to 5, it will be discarded, and 3.5 and 3.8 will also change to 3. This is consistent with C# / operation.

### II. Javascript round to the specified decimal

Round to the specified decimal using the toFixed() method in javascript, it will automatically round to, just round to a few decimals and enter a few in parentheses, the following is a specific example:

var an = 1.234, bn = 0.3755;
var a = an.toFixed(2);//round to 2 decimal places

b = bn.toFixed(2);//round to 2 decimal places
c = bn.toFixed(3);//round to 2 decimal places

alert("a=" + a + "; b=" + b + "; c=" + c);

Output result: a=1.23; b=0.38; c=0.376

It can be seen from the output that no matter whether two or three decimals are retained, they are rounded.