A Guide to Rounding Numbers in JavaScript

1663122397rounding numbers in javascript


This article describes different ways to round numbers in JavaScript. This includes using JavaScript math functions and other methods of rounding decimal places. It also discusses pitfalls to watch out for when rounding numbers.

JavaScript rounding

When working with numbers, such as calculating average prices or working with random numbers, you may perform calculations that result in fractional parts that need to be rounded to whole numbers.Thankfully, JavaScript’s Math Objects provide several ways to round numbers to integer values.

This example uses two of the most important mathematical constants to demonstrate different types of rounding. Pi is the ratio of the circle’s circumference to its diameter. e is the base of the natural logarithm, commonly known as “Euler’s number”. Both of these values ​​are Math objects, but let’s assign them to some variables to make them easier to work with.

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

Pro-tip: You can also use object splitting to make this assignment in one line.

const { PI,E } = Math

With these constants defined, let’s look at some ways to round numbers in JavaScript.

Rounding Numbers in JavaScript with Math.round

The first way to introduce Math.roundThis is the easiest option and just rounds numbers with fractional parts to the nearest whole number. Use this rule: If a number is exactly halfway between two integers, it will be rounded. UpFor example, 2.5 is rounded up to 3.

To use this method, simply supply the number you want to round as an argument.

<< 2

<< 3

<< 3

<< 3

<< 3

Math.round() Useful when you want to round a number to the nearest integer value. For example, to calculate the average score of 3 tests, add the 3 scores and divide by 3.This may not be an integer, so use Math.round() To round 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 will look at is Math.floor. This always rounds the value under to the bottom integer (the name means the number is being pushed down floor):

<< 2

<< 2

<< 2

<< 3

<< 2

common usage of Math.floor It’s time to create a random integer. rounding under Integers start at zero and guarantee that each integer is equally likely to be returned. Arrays in JavaScript are indexed by zero, so starting from zero is generally useful. The example below shows how to select a random element from an array using: Math.floor:

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

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

rounding under Use Math.floor The code above guarantees to return indices from 0 to 4, so all elements in the array have an equal chance of being selected.

Rounding numbers with Math.ceil

Speaking of rounding up, this is exactly what Math.ceil To do.Origin of the name sealing and opposite floorwhich means the value is leading UpThis method works the same as all other methods. Just specify the number you want to round up as an argument.

<< 3

<< 3

<< 3

<< 4

<< 3

But when do you need to round up a number? A common use is when you need to calculate how many containers you need for something. For example, let’s say you have a music site with playlists, each with 10 of her songs. If someone uploaded his 82 songs, you’d have to calculate how many playlists to create. This is done by dividing the number of songs by . 10 (number of songs in each playlist):

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

use Math.round round this under To 8 …but there is no playlist for the last two songs.In such cases you should always round Up To add the remaining containers:

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

Rounding numbers with Math.trunc

The next method we will look at is Math.trunc. This is not strictly a rounding actually truncate A number provided as an argument. It basically removes the fractional part of the number and leaves only the integer part, as shown in the example below.

<< 2

<< 2

<< 2

<< 3

<< 2

at first glance, Math.trunc seems identical to Math.floor; Indeed, all the examples shown so far yield the same result. However, these two methods behave differently when a negative value is given as an argument, as shown in the example below.

<< -3

<< -2

The difference occurs when negative numbers are truncated Math.floorwhich drops to the next smaller integer, but truncating a negative value is the same as rounding it Up.

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

<< -2

<< -2

All of these methods are very useful, but they have the limitation that they always return an integer value. What if you want to round a number to a specific number of decimal places or significant figures?

Round numbers to decimal places in JavaScript

we have already seen it Math.round Rounds a number to the nearest integer. Unfortunately, Math The object does not provide a way to round a number more precisely to a specific number of decimal places. Thankfully Number type has some built-in methods. can do this. Let’s see them.

Rounding to decimal places with Number.toFixed

This is a numeric method. i.e. called by the number itself. Rounds a decimal number to the number of decimal places specified as an argument.

<< "2.44"

One thing to note is that the values ​​are returned as string. method call Number Functions that return numeric results:

<< 2.44

Another thing to note: If you try to apply this method to a number that is already an integer, calling the method with a single dot will raise an error.

<< SyntaxError

A single dot cannot be used to call integer methods. This is because it is not clear whether the dot is a method call operator or a decimal point. To avoid this, enclose the integer in parentheses or use two dots to make it clear that you are calling a method rather than writing out a numeric literal with a decimal point.

<< "2.00"

<< "2.00"

If no argument is given, the number is rounded to the nearest integer (but returned as a string).

<< "3"

<< "3"

A common use case for rounding to a set number of decimal places is when dealing with currencies. For example, if you want to display the price of something to the nearest cent in US dollars. For example, let’s say you have an e-commerce site with a promotion that gives him 15% off items in his shopping cart. Discounted prices may need to be rounded before being 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 using: Number.toFixed:

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

Note: For more information on issues you may face, toFixed()see Number().toFixed() rounding error: broken but fixable.

Round a number to decimal places with Number.toPrecision

of Number.toPrecision The method is Number.toFixed method, but rounds the number to a fixed number of significant digits.

If you need to easily remember significant digits, that basically means using only the first non-zero digit. If the number is large, the final answer is also filled with zeros. For example, 53,863 rounded to 2 significant figures is 54,000. This is because 5 and 3 are the first two non-zero digits, and the next digit is 8, so it rounds up. You must add trailing zeros so that the rounded value is a good approximation of the original number.

You can also round decimals in a similar way. For example, 0.00000623978 is rounded to 0.0000062, truncated because 6 and 2 are the first non-zero digits and the next digit is 3.

To use this method, simply call it on a number, specifying the number of significant digits as an argument (note that you must enclose the integer in parentheses before calling the method on an integer. please give me).

<< "5.4e+4"

<< 0.0000062"

Note that all values ​​are returned as strings and you can use exponential notation such as “5.4e+4” instead of “54000”.

As before, replace the method call with Number function:

<< 54000

A common use for rounding to a given significant digit is when you are dealing with a large number and you don’t know how large it will be. For example, if you wanted to report the number of times your most recent post was liked, would it be rounded to 10, 100, or 1000? In a way, this depends on how popular it is. If you only have 8 likes, you don’t want to round to the 100’s place, but if you have thousands of likes, it’s silly to round to the 10’s place. The solution is to round the significant digits to 1 digit.

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

<< 8
<< 400
<< Number(poplularPost.toPrecision(1))
<< 80000

Issues with rounding numbers in JavaScript

There are a few things to keep in mind when rounding numbers in JavaScript (or any other programming language). As you probably know, computers store all data, including numbers, as a binary representation. JavaScript stores numbers as 32-bit single-precision binary values.

The problem with this is that base 10 numbers cannot be represented exactly in base 2. This usually doesn’t cause any problems, but it does produce strange results like:

0.1 + 0.2 === 0.3
<< false

This is because 0.1 and 0.2 cannot be represented. Exactly They are binary and adding them together gives a slight error.

of Math The object has another method called fround, returns the nearest number that can be represented using 32 bits. For example, 0.6125 can be exactly represented in binary as 0.101, so this returns the same value.

<< 0.625

But as we saw above, 0.1 cannot be represented exactly in 32 bits. Math.fround Gives the closest representable number.

<< 0.10000000149011612

As you can see, it’s very close to 0.1, but very Slightly expensive. In most real-world cases this will not cause any problems, but you may get strange behavior when trying to round numbers.

<< "3.5"

This happens because 32 bits cannot represent the decimal number 3.55 exactly.can be used Math.fround To see how it’s actually represented:

<< 3.549999952316284

As you can see, it’s actually represented by the floating point number 3.549999952316284 and rounded. under to 3.5.

These problems with rounding numbers in JavaScript don’t occur very often, but you should be careful if you do rounding frequently, especially if exact results are important.

Which method should I use for rounding numbers?

Of all the rounding methods presented in this rounding summary, you might ask which one is the best to use. As always, the answer is “it depends”.

if you just want to round a number to the nearest integeryou can’t go wrong Math.roundbut you should also consider using Math.floor Also Math.ceil If you want to always round down or round up no matter what the fractional part is.And consider using Math.trunc Alternatively, if you also plan to round negative numbers.

if you need Round to a specified number of decimal places or significant figuresyou should use Number.toFixed Also Number.toPrecisionNote, however, that these two methods are called on numbers and return strings.

You can see all the different types of rounding examples covered in this article in the following CodePen demos.

look at the pen
SitePoint rounding with SitePoint (@SitePoint)
with a code pen.

With all these different methods available, rounding numbers will not be a problem from now on.

If you found this article useful, you may also like:


Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    C2fYudiRqEfLr4jV4HK33j 1200 80

    iPhone 15: What we know so far

    UeHpVSg7S6sSwoLkjWbMdL 1200 80

    Everything we know about the Nvidia RTX 4060