 ## A Guide to Rounding Numbers in JavaScript

In this article, we’ll explore the different ways to round numbers in JavaScript. This would involve using JavaScript math functions and other methods to round to decimal places. We’ll also cover gotchas to keep in mind when rounding numbers.

## javascript rounding

When working with numerical values, we can sometimes perform calculations that end up with fractional parts that need to be rounded to a whole number—such as when you’re working with an average value, or dealing with random numbers. thank you javascript `Math` The object provides several methods for rounding numbers to an integer value.

In our examples, we’ll use the two most important mathematical constants to demonstrate the different types of rounding: exemplarywhich is the ratio of the circumference of a circle to its diameter, and I, which is the base of the natural logarithm and is also known as the “Euler number”. Both of these are properties of value `Math` objects, but let’s assign them to some variables to make them easier to deal with:

``````const PI = Math.PI
const E = Math.E
``````

Pro tip: You can also make this assignment in one line using object destructuring:

``````const  PI,E  = Math
``````

Now that we have these constants defined, let’s take a look at some ways to round numbers in JavaScript.

## Rounding numbers in Javascript with Math.round

the first way we’ll see `Math.round`, This is the most straightforward option, and rounds any number with a decimal part to the nearest whole number. It uses this rule: if a number is exactly in the middle of two integers, it will be rounded down UP, For example, 2.5 rounds up to 3.

To use this method, we simply provide the number we want to round as an argument:

``````Math.round(2.3)
<< 2

Math.round(2.921)
<< 3

Math.round(2.5)
<< 3

Math.round(PI)
<< 3

Math.round(E)
<< 3
``````

`Math.round()` This comes in handy if you want to round a number to the nearest integer value. For example, if you were calculating the average score on three tests, you would add the three scores and divide by three. This may not result in a whole number, so you would use `Math.round()` To round it to the nearest value:

``````const test1 = 86;
const test2 = 93;
const test3 = 95;
const average = Math.round((test1+test2+test3)/3);
<< 91
``````

## Rounding numbers with Math.floor

the next method we’ll look at `Math.floor`, it always rounds a value below to integer down (the name means that the number is being pushed down destination,

``````Math.floor(2.3)
<< 2

Math.floor(2.921)
<< 2

Math.floor(2.5)
<< 2

Math.floor(PI)
<< 3

Math.floor(E)
<< 2
``````

is a common use of `Math.floor` while generating random integers is, Sphericity below This ensures that the integer will start at zero and that each integer returned will have an equal chance. Starting at zero is generally useful, as arrays in JavaScript are zero-indexed, so rounding down will ensure that the first element in the array can be selected. The example below shows how a random element can be selected from an array `Math.floor`,

``````const fruit = ["🍏","🍌","🍓","🍋","🍐"]

const randomFruit = fruit[Math.floor(Math.random()*fruit.length)]
<< "🍓"
``````

Sphericity below using the `Math.floor` In the code above this ensures that an index between 0 and 4 is returned so each element in the array has an equal chance of being selected.

## Rounding numbers with math.ceil

Speaking of rounding up, this is exactly what `Math.ceil` does. name comes from ceiling and vice versa destinationwhich means the value is going UP, The method works in the same way as all the others. Just provide the number you want to round as an argument:

``````Math.ceil(2.3)
<< 3

Math.ceil(2.921)
<< 3

Math.ceil(2.5)
<< 3

Math.ceil(PI)
<< 4

Math.ceil(E)
<< 3
``````

But when would you need to round a number? A common use is if you need to figure out how many containers you need for something. For example, let’s say you have a music site that includes playlists, and each playlist has ten songs. If someone uploads 82 songs, that’s how many playlists you need to make. This is done by dividing the number of songs by `10` (number of songs on each playlist):

``````const songsPerPlaylist = 10;
const numberOfSongs = 82;
const numberOfPlaylists = numberOfSongs/songsPerPlaylist;
<< 8.2
``````

using the `Math.round` it will be round below To `8` … but then we wouldn’t have a playlist for the last two songs! In such cases we always need to round up UP To have an extra container for any leftovers:

``````const numberOfPlaylists = Math.ceil(numberOfSongs/songsPerPlaylist);
<< 9
``````

## Rounding numbers with Math.trunc

the next method we’ll look at `Math.trunc`, This isn’t strictly speaking a rounding function; it really truncates The number provided as an argument. It basically removes the decimal part of the number, leaving only the integer part, as can be seen in the examples below:

``````Math.trunc(2.3)
<< 2

Math.trunc(2.921)
<< 2

Math.trunc(2.5)
<< 2

Math.trunc(PI)
<< 3

Math.trunc(E)
<< 2
``````

at first sight, `Math.trunc` looks like `Math.floor`, Of course the examples given so far all give the same result. However, these two methods behave differently when a negative value is provided as an argument, as can be seen in the example below:

``````Math.floor(-2.3)
<< -3

Math.trunc(-2.3)
<< -2
``````

The difference occurs because, when rounding to a negative number using `Math.floor`This rounds up to the next lowest integer, while truncating a negative value is equivalent to rounding down UP,

`Math.ceil` returns the same value as `Math.trunc` When the argument is a negative number:

``````Math.trunc(-2.3)
<< -2

Math.ceil(-2.3)
<< -2
``````

All these methods can be very useful, but they have the limitation that they always return integer values. What if we want to round a number to a certain number of decimal places or significant digits?

## Rounding numbers to decimal places in Javascript

we have already seen `Math.round` Will round the numbers to the nearest integer. unfortunately `Math` The object does not provide a method to more precisely round numbers to a specified number of decimal places. Thank God, `Number` The type has some built-in methods can do Do it Let’s have a look at them.

### Rounding to decimal places with Number.toFixed

It is a number method, which means it is called by number only. It rounds a decimal number up to the given number of decimal places, provided as an argument:

``````2.4387587.toFixed(2)
<< "2.44"
``````

One thing to note is that the value is returned as a string, You can achieve this by wrapping the method call in `Number` Function, which will convert the result back to a number:

``````Number(2.4387587.toFixed(2))
<< 2.44
``````

A few other things to watch out for: If you try to apply this method to a number that’s already an integer, you’ll get an error if you just use a dot to call the method:

``````2.toFixed(2)
<< SyntaxError
``````

You cannot call methods on integers using a dot, because it is not clear whether the dot is a method call operator or a decimal point. To get around this, you can either put the integer in parentheses or use two dots to make it clear that you’re calling a method instead of writing a literal number with a decimal point:

``````(2).toFixed(2)
<< "2.00"

2..toFixed(2)
<< "2.00"
``````

If no argument is supplied, the number will be rounded to the nearest integer (but returned as a string):

``````PI.toFixed()
<< "3"

E.toFixed()
<< "3"
``````

A common use case is to round to a certain number of decimal places when dealing with currency – for example, if you want to provide the price of something in US dollars rounded to the nearest percent. Let’s say you have an e-commerce site that is promoting 15% off everything in the shopping cart. Discounted pricing may need to be completed before it is displayed:

``````const item1Price = 2.99
const item2Price = 4.99
const item3Price = 6.20

const totalPrice = item1Price + item2Price + item3Price
const discountedPrice = 0.85 * totalPrice
<< 12.052999999999999
``````

This can be easily fixed by using `Number.toFixed`,

``````const discountedPrice = (0.85 * totalPrice).toFixed(2)
<< "12.05"
``````

Note: For more information about the issues you may encounter `toFixed()`See Number().toFixed() Rounding Errors: Broken But Fixable.

### Rounding numbers to decimal places with Number.toPrecision

`Number.toPrecision` works like method `Number.toFixed` method, but it rounds to a certain number of numbers vital statistics,

If you need a quick reminder of significant digits, it basically just means using the first non-zero digit. For larger numbers, the final answer will also be padded out with zeros. For example, converting the number 53,863 to two significant digits becomes 54,000. This is because 5 and 3 are the first two non-zero digits, and it rounds up because the next digit is 8. We need to add zeros at the end to make sure that the rounded value is a reasonable approximation to the original number.

You can round off decimals in a similar way. For example, 0.00000623978 would convert to 0.0000062 to two significant digits because 6 and 2 are the first non-zero digits and it rounds down because the next digit is 3.

To use this method, simply call it on Number , providing the number of significant digits as an argument (remember that integers must be placed in parentheses before calling a method on them):

``````(53863).toPrecision(2)
<< "5.4e+4"

0.00000623978.toPrecision(2)
<< 0.0000062"
``````

Note that all values ​​are returned as strings, and exponential notation may be used – such as “5.4e+4” instead of “54000”.

As before, we can be sure that a number is returned by wrapping the method call in `Number` Celebration:

``````Number((53863).toPrecision(2))
<< 54000
``````

A common use of rounding up to a given number of significant digits is when you’re working with large numbers and you’re not sure how large they’re going to be. For example, let’s say you want to report how many times your latest post has been “liked”, do you round it to the nearest 10, 100 or 1000? In a way, it depends on how popular it is; If it only gets 8 likes, you don’t want to round it to the nearest 100, but if it gets thousands of likes, rounding it to the nearest 10 seems silly.

``````const unpopularPost = 8;
const quitePopularPost = 387;
const poplularPost = 79671;

Number(unpopularPost.toPrecision(1))
<< 8
Number(quitePopularPost.toPrecision(1))
<< 400
Number(poplularPost.toPrecision(1))
<< Number(poplularPost.toPrecision(1))
<< 80000
``````

## Problems with rounding numbers in Javascript

There are a few things to watch out for when rounding numbers in JavaScript (or any programming language for that matter). As you probably know, computers store all data – including numbers – as a binary representation. javascript store numbers 32-bit single precision binary value.

the problem with this is that some base 10 number cannot be displayed accurately in base 2, This usually doesn’t cause any problems, but it does produce some weird results like this:

``````0.1 + 0.2 === 0.3
<< false
``````

This is because 0.1 and 0.2 cannot be represented Absolutely in binary, and a slight error occurs while adding them.

`Math` another method of the object is called `fround`, which gives the closest number that can be represented using 32-bits. For example, 0.6125 can be represented as 0.101 in binary, so it will return the same value:

``````Math.fround(0.625)
<< 0.625
``````

But, as we saw above, 0.1 cannot be represented exactly in 32-bits. `Math.fround` shows us the closest number that can be represented:

``````Math.fround(0.1)
<< 0.10000000149011612
``````

As you can see, it is very close to 0.1, but very slightly higher. In most practical cases, this won’t cause a problem, but sometimes it can cause some strange behavior when you try to round some numbers:

``````3.55.toFixed(1)
<< "3.5"
``````

This happens because the decimal 3.55 cannot be represented accurately using 32-bits. we can use `Math.fround` To see how it is actually represented:

``````Math.fround(3.55)
<< 3.549999952316284
``````

As you can see, this is actually represented by the floating point number 3.549999952316284, which rounds to below 3.5.

These problems don’t happen often with rounding numbers in JavaScript, but they’re certainly something you should be aware of if you’re doing a lot of rounding – especially when it’s important that the result be accurate.

## What methods should I use for rounding numbers?

With all the rounding methods presented in this rounding roundup, you may be asking which is the best to use. As always, the answer is, “it depends”.

if you just want round a number to the nearest integeryou can’t do much wrong `Math.round`but you should also consider using `Math.floor` either `Math.ceil` If you want to always round down or up, regardless of the decimal part. and consider using `Math.trunc` Instead if you plan to round to negative numbers as well.

if you need to round to a given number of decimal places or significant digitsyou have to use `Number.toFixed` either `Number.toPrecision`, But keep in mind that these two methods are called by Number and return a string.

You can see an example of all the different types of rounding covered in this article in the following CodePen demo.

see pen
sitepoint rounding
by sitepoint (@SitePoint,
Feather codepen,

With all these different methods available, you should have no problem rounding numbers from now on.