Javascript – Rounding floating point numbers

There are six different functions in JavaScript’s Math library for rounding floating point numbers:

  • abs()
  • ceil()
  • floor()
  • round()
  • trunc()
  • fround()

What is the difference between these functions?

abs()

abs() is the absolute value of a number. Mathematically speaking, it is the distance of a number from zero. As a distance cannot be negative, the absolute value is always the positive value of a number:

Math.abs(7.89012) = 7.89012
Math.abs(-7.89012) = 7.89012

ceil()

ceil() rounds up a number to the nearest integer value greater than or equal to the given number:

Math.ceil(7.1) = 8
Math.ceil(7.8) = 8
Math.ceil(-7.1) = -7
Math.ceil(-7.8) = -7

Please note that the next largest integer from -7.1 is not -8, but -7.

floor()

floor() is the counterpart to ceil(), so it rounds the given number to the next smaller or equal number to the given number:

Math.floor(7.1) = 7
Math.floor(7.8) = 7
Math.floor(-7.1) = -8
Math.floor(-7.8) = -8

round()

round() rounds the given number to the nearest whole number:

Math.round(7.1) = 7
Math.round(7.8) = 8
Math.round(-7.1) = -7
Math.round(-7.8) = -8

The function works mathematically correctly:

math.round(7.49) = 7
math.round(7.5) = 8

trunc()

Math.trunc(7.1) = 7
Math.trunc(7.8) = 7
Math.trunc(-7.1) = -7
Math.trunc(-7.8) = -7

fround()

This function is only required in special situations where you have to work with 32-bit numbers, e.g. in graphics or audio programming. It enables more precise rounding than the more general round().
Here is a more detailed explanation than is useful in this article.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *