DEV Community

Cover image for JavaScript – Rounding floating point numbers
Latz
Latz

Posted on

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.

(Foto von Mika Baumeister auf Unsplash)

Top comments (1)

Collapse
 
efpage profile image
Eckehard • Edited

Some programming languages provide a handy option to set a certain number of decimals on round(). To get the functionality, you can extend the standard Math-library:

Math._round = Math.round
Math.round = (f, n = 0) => { 
  let m = Math.pow(10, n)
  return (Math._round(f * m) / m)
}

Math.round(3.5689,2) => 3.57
Enter fullscreen mode Exit fullscreen mode

See more useful hints on Math here