Home >Web Front-end >JS Tutorial >A Guide to Rounding Numbers in JavaScript
This article explores various number rounding methods in JavaScript, including using JavaScript mathematical functions and other methods of rounding to decimal places. We will also introduce issues that need to be paid attention to when rounding numbers.
Math.round
, Math.floor
, Math.ceil
, and Math.trunc
. Math.round
Round to the nearest integer, Math.floor
Round down, Math.ceil
Round up, Math.trunc
Truncate the fractional part of the number. Number.toFixed
and Number.toPrecision
methods for rounding numbers to specific decimal places or significant numbers. These methods return the rounded number as a string. Math.round
, Math.floor
, Math.ceil
, and Math.trunc
differ. For example, Math.floor
rounds the negative number down to the next smallest integer, while Math.trunc
truncates the fractional part, effectively rounding it upwards. Math.fround
method can be used to find the closest representable number of 32 bits. Math.round
is a good general choice for rounding to the closest integer, but Math.floor
, Math.ceil
or Math.trunc
may be better suited to always round down or up, or to deal with negative numbers. Number.toFixed
or Number.toPrecision
applies to rounding to a specific decimal or significant number. When processing numeric values, we sometimes perform calculations that end up producing fractional portions that need to be rounded to the integers—for example, when you calculate the average price or process random numbers. Fortunately, JavaScript's Math
object provides many ways to round numbers to integer values.
In our example, we will demonstrate different types of rounding using two most important mathematical constants: π (the ratio of the perimeter of a circle to its diameter) and e (the base of natural logarithm, also known as "Euler number"). Both values are properties of Math
objects, but let's assign them to some variables to make it easier to handle:
<code class="language-javascript">const PI = Math.PI; const E = Math.E;</code>
Pro tip: You can also use object destruction to make this assignment in a line:
<code class="language-javascript">const { PI, E } = Math;</code>
Now that we have defined these constants, let's take a look at some methods for rounding numbers in JavaScript.
Math.round
. This is the most straightforward choice, it just rounds any number with a fractional part to the closest integer. It uses the following rule: If a number is exactly between two integers, round it up. For example, 2.5 will round up to 3. Math.round
<code class="language-javascript">const PI = Math.PI; const E = Math.E;</code>If you want to round the number to the nearest integer value,
is very convenient. For example, if you are calculating the average score of three tests, add the three scores and divide them by three. This may not get an integer, so you can round it to the closest value using Math.round()
: Math.round()
<code class="language-javascript">const { PI, E } = Math;</code>Rounding numbers using
Math.floor
. This always rounds the value down to the integer below (name means the number is pushed down to the "floor"): Math.floor
<code class="language-javascript">Math.round(2.3); // 因为更接近2,所以向下舍入 Math.round(2.921); // 因为更接近3,所以向上舍入 Math.round(2.5); // 因为正好位于中间,所以向上舍入 Math.round(PI); Math.round(E);</code>
is to create random integers. Rounding down ensures that the integer starts from zero and that each integer has the same chance of being returned. Starting from zero is often useful because arrays in JavaScript are zero-indexed, so rounding down will ensure that the first element in the array can be selected. The following example shows how to select a random element from an array using Math.floor
: Math.floor
<code class="language-javascript">const test1 = 86; const test2 = 93; const test3 = 95; const average = Math.round((test1 + test2 + test3) / 3);</code>The above code uses
rounding down to ensure that an index between 0 and 4 is returned, so each element in the array has the same chance of being selected. Math.floor
Math.ceil
does. This name comes from "ceiling", which, contrary to "flooring", means that the value is rising. This method works the same way as all other methods. Just provide the number you want to round up as the parameter: Math.ceil
<code class="language-javascript">Math.floor(2.3); // 向下舍入到2 Math.floor(2.921); // 向下舍入到2 Math.floor(2.5); // 向下舍入到2 Math.floor(PI); Math.floor(E);</code>But when do you need to round up a number? A common usage is if you need to calculate how many containers you need to hold something. For example, suppose you have a music website that contains playlists, each playlist contains ten songs. If someone uploads 82 songs, you need to figure out how many playlists you want to create. This is done by dividing the number of songs by 10 (the number of songs in each playlist):
<code class="language-javascript">const fruit = ["?", "?", "?", "?", "?"]; const randomFruit = fruit[Math.floor(Math.random() * fruit.length)];</code>Using
will round it down to 8... However, we won't create a playlist for the last two songs! In this case we always need to round up so that we can provide an extra container for any remainder: Math.round
<code class="language-javascript">Math.ceil(2.3); // 向上舍入到3 Math.ceil(2.921); // 向上舍入到3 Math.ceil(2.5); // 向上舍入到3 Math.ceil(PI); Math.ceil(E);</code>Rounding numbers using
Math.trunc
. Strictly speaking, this is not a rounding function; it is actually truncating the provided parameter numbers. It basically just deletes the decimal part of the number, leaving only the integer part, as shown in the following example: Math.trunc
<code class="language-javascript">const PI = Math.PI; const E = Math.E;</code>
At first glance, Math.trunc
seems to be the same as Math.floor
; of course, all the examples given so far give the same results. However, when a negative value is provided as a parameter, the two methods behave differently, as shown in the following example:
<code class="language-javascript">const { PI, E } = Math;</code>The difference occurs because when using
to round down the negative number, it rounds down to the next smallest integer, and truncating a negative value is equivalent to rounding it upwards. Math.floor
returns the same value as Math.ceil
: Math.trunc
<code class="language-javascript">Math.round(2.3); // 因为更接近2,所以向下舍入 Math.round(2.921); // 因为更接近3,所以向上舍入 Math.round(2.5); // 因为正好位于中间,所以向上舍入 Math.round(PI); Math.round(E);</code>All of these methods are very useful, but they have a limitation that they always return integer values. What if we want to round numbers to a specific decimal or significant number?
Round numbers to decimal places in JavaScript
will round the number to the nearest integer. Unfortunately, the Math.round
object does not provide any way to round numbers to a specific decimal place with more precise accuracy. Fortunately, the Math
type has some built-in ways to do this. Let's take a look at them. Number
Number.toFixed
One thing to note about is that this value is returned as a
<code class="language-javascript">const test1 = 86; const test2 = 93; const test3 = 95; const average = Math.round((test1 + test2 + test3) / 3);</code>string
. You can solve this problem by wrapping the method call in a function, which converts the result back to a number:
Number
<code class="language-javascript">Math.floor(2.3); // 向下舍入到2 Math.floor(2.921); // 向下舍入到2 Math.floor(2.5); // 向下舍入到2 Math.floor(PI); Math.floor(E);</code>
You cannot call methods on integers using a single point, because it is not clear whether the point is a method call operator or a decimal point. To fix this, you can put integers in brackets or use two dots to clearly indicate that you are calling a method instead of writing a numeric literal with a decimal point:
<code class="language-javascript">const fruit = ["?", "?", "?", "?", "?"]; const randomFruit = fruit[Math.floor(Math.random() * fruit.length)];</code>
If no argument is provided, the number will be rounded to the nearest integer (but returned as a string):
<code class="language-javascript">Math.ceil(2.3); // 向上舍入到3 Math.ceil(2.921); // 向上舍入到3 Math.ceil(2.5); // 向上舍入到3 Math.ceil(PI); Math.ceil(E);</code>
A common use case for rounding to a few decimal places set is dealing with currency—for example, if you want to offer the price of something in the closest dollar to cents. Suppose you have an e-commerce website with a promotion in progress and you can get a 15% discount on any item in your shopping cart. Before displaying the discounted price, it may be necessary to round it:
<code class="language-javascript">const songsPerPlaylist = 10; const numberOfSongs = 82; const numberOfPlaylists = numberOfSongs / songsPerPlaylist;</code>
This can be easily fixed using
<code class="language-javascript">const numberOfPlaylists = Math.ceil(numberOfSongs / songsPerPlaylist);</code>:
Number.toFixed
<code class="language-javascript">Math.trunc(2.3); // 只留下2 Math.trunc(2.921); // 只留下2,即使它更接近3 Math.trunc(2.5); // 只留下2 Math.trunc(PI); Math.trunc(E);</code>Note: For more information about the
issues you may have, see Number().toFixed() rounding error: corrupted but fixable. If you need a quick reminder of a valid number, it basically means only using the first non-zero number. For large numbers, the final answer will also be filled with zeros. For example, the number 53,863 rounded to two significant digits will become 54,000. This is because 5 and 3 are the first two non-zero numbers, and since the next number is 8, it rounds upwards. We need to add zeros at the end to make sure the rounded value is a reasonable approximation of the original number. You can round decimals in a similar way. For example, 0.00000623978 will round to 0.0000062 to two significant digits, because 6 and 2 are the first two non-zero numbers, and since the next digit is 3, it rounds down. To use this method, just call it on the number and provide the number of significant numbers as arguments (remember, integers need to be placed in brackets before calling them): Note that all values are returned as strings and can be used with exponential notation—for example "5.4e 4" instead of "54000". As mentioned earlier, we can ensure that a number is returned by wrapping the method call in the A common use of rounding to a given significant number is when you work with large numbers and are not sure how big they are. For example, suppose you want to report the number of times the latest post was "liked", did you round it to the closest 10, 100, or 1000? To some extent, it depends on how popular it is; if it gets only 8 likes, you don't want to round it to the closest 100, but if it gets thousands of likes, round it to The closest 10 seems stupid. The solution is to round it to a significant number: There are some things to note when rounding numbers in JavaScript (or any programming language). As you may know, a computer stores all data (including numbers) as a binary representation. JavaScript stores numbers as 32-bit single-precision binary values. One of the problems with doing this is that some decimal numbers cannot be represented accurately in binary. This usually does not cause any problems, but it does lead to some weird results, such as: This is because 0.1 and 0.2 cannot be represented accurately in binary and produce slight errors when adding them together. However, as we saw above, 0.1 cannot be expressed accurately in 32 bits. As you can see, it is very close to 0.1, but is very slightly higher. In most practical cases this does not cause any problem, but it occasionally causes some weird behavior when you try to round some numbers: This happens because decimal 3.55 cannot use 32-bit precise representation. We can use As you can see, it is actually represented by the floating point number 3.549999952316284, which rounds down to 3.5. These problems with rounding numbers in JavaScript don't happen often, but you should definitely pay attention to these issues if you are doing a lot of rounding, especially if the results must be accurate. With all the rounding methods described in this article, you may ask which method is best. The answer is always "it depends". If you just want to round numbers to the closest integer, you won't go wrong with If you need to round to a given decimal or significant number, you must use You can see all the different types of rounding examples described in this article in the CodePen demonstration below. With all these different methods, you shouldn't have any issues with rounding numbers in the future. If you find this article useful, you might also like these: How to round numbers to closest integers in JavaScript? You can use the Can I round the numbers to a specific decimal number? Yes, you can round numbers to specific decimal places using the Can I use Is a rounding error happening in JavaScript? Yes, rounding errors may occur due to the way floating point operations work in your computer. It is important to pay attention to potential accuracy issues, especially when dealing with very large or very small numbers. In this case, consider using a library like decimal.js for more precise arithmetic operations. toFixed()
Round to decimal places using
The Number.toPrecision
Number.toPrecision
method works similarly to the Number.toFixed
method, but it rounds the numbers to a fixed number of significant numbers. <code class="language-javascript">const PI = Math.PI;
const E = Math.E;</code>
Number
function: <code class="language-javascript">const { PI, E } = Math;</code>
<code class="language-javascript">Math.round(2.3); // 因为更接近2,所以向下舍入
Math.round(2.921); // 因为更接近3,所以向上舍入
Math.round(2.5); // 因为正好位于中间,所以向上舍入
Math.round(PI);
Math.round(E);</code>
Issues of rounding numbers in JavaScript
<code class="language-javascript">const test1 = 86;
const test2 = 93;
const test3 = 95;
const average = Math.round((test1 + test2 + test3) / 3);</code>
Math
object has another method called fround
which returns the closest number that can be represented using 32-bits. For example, 0.6125 can be expressed precisely as binary 0.101, so this will return the same value: <code class="language-javascript">Math.floor(2.3); // 向下舍入到2
Math.floor(2.921); // 向下舍入到2
Math.floor(2.5); // 向下舍入到2
Math.floor(PI);
Math.floor(E);</code>
Math.fround
shows us the closest number that can be represented: <code class="language-javascript">const PI = Math.PI;
const E = Math.E;</code>
<code class="language-javascript">const { PI, E } = Math;</code>
Math.fround
to see how it actually represents it: <code class="language-javascript">Math.round(2.3); // 因为更接近2,所以向下舍入
Math.round(2.921); // 因为更接近3,所以向上舍入
Math.round(2.5); // 因为正好位于中间,所以向上舍入
Math.round(PI);
Math.round(E);</code>
What methods should I use to round numbers?
Math.round
, but if you always want to round down or up, regardless of the fractional part, you should also consider using Math.floor
or Math.ceil
. If you are also planning to round negative numbers, consider using Math.trunc
instead. Number.toFixed
or Number.toPrecision
. But please note that both methods are called by numbers and return a string.
FAQs about rounding numbers in JavaScript
Math.round()
function to round the number to the nearest integer. For example, Math.round(3.14)
will get 3 and Math.round(4.76)
will get 5. Math.round()
, Math.floor()
and Math.ceil()
? Math.round()
Round to the nearest integer, Math.floor()
Round down to the nearest integer, Math.ceil()
Round up to the nearest integer. toFixed()
method. For example, let roundedNumber = 3.14159.toFixed(2)
will get 3.14. Math.round()
How to deal with numbers with .5 decimal parts? Math.round()
Use "rounding" logic, which means that when the fractional part is exactly .5, it rounds to the closest even integer. For example, the result of Math.round(2.5)
is 2 and the result of Math.round(3.5)
is 4. Math.round()
to round positive and negative numbers? Yes, Math.round()
works with positive and negative numbers. It rounds positive numbers as usual and rounds negative numbers to zero.
The above is the detailed content of A Guide to Rounding Numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!