The methods Math.trunc()
, Math.floor()
, and Math.ceil()
differ in how they handle the fractional part of numbers. Let us look at an example.
For positive values like 2.9
, both Math.trunc()
and Math.floor()
return 2 by either truncating the decimal or rounding down, while Math.ceil()
rounds up to 3.
For negative values like -2.9
, Math.trunc()
removes the decimal, resulting in -2, Math.floor()
rounds down to the smaller integer -3, and Math.ceil()
rounds up to -2.
These differences are particularly important when deciding whether to simply remove the fractional part or adjust the value directionally.
Practical Use Cases
Use Math.trunc()
when you need to discard the fractional part of a number without regard for its sign. For example, calculating integer parts of measurements.
Use Math.floor()
when you need to round down, especially for negative numbers. For example, determining a customer's maximum eligible discount tier based on a spent amount.
Use Math.ceil()
when rounding up is required, such as in calculating the minimum number of packages required to ship a certain number of items.
By understanding these differences, you can choose the appropriate method based on your specific use case.