• Skip to main content
  • Skip to search
  • Skip to select language
  • Get MDN Plus
  • English (US)

Math.round()

The Math.round() static method returns the value of a number rounded to the nearest integer.

Return value

The value of x rounded to the nearest integer.

Description

If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.

Note: This differs from many languages' round() functions, which often round half-increments away from zero , giving a different result in the case of negative numbers with a fractional part of exactly 0.5.

Math.round(x) is not exactly the same as Math.floor(x + 0.5) . When x is -0, or -0.5 ≤ x < 0, Math.round(x) returns -0, while Math.floor(x + 0.5) returns 0. However, neglecting that difference and potential precision errors, Math.round(x) and Math.floor(x + 0.5) are generally equivalent.

Because round() is a static method of Math , you always use it as Math.round() , rather than as a method of a Math object you created ( Math has no constructor).

Using round

Specifications, browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

JS Reference

Html events, html objects, other references, javascript math.round(), definition and usage.

The Math.round() method rounds a number to the nearest integer.

2.49 will be rounded down (2), and 2.5 will be rounded up (3).

JavaScript Rounding Functions

Advertisement

Return Value

Browser support.

Math.round() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

math rounding javascript

Get certified by completing a course today!

Subscribe

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Your Suggestion:

Thank you for helping us.

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, web certificates, get certified.

A Guide to Rounding Numbers in JavaScript

math rounding javascript

In this article, we’ll explore various ways of rounding numbers in JavaScript. This will include using JavaScript math functions, and other methods for rounding to decimal places. We’ll also cover gotchas to watch out for when rounding numbers.

JavaScript Rounding

When dealing with numerical values, we can sometimes perform calculations that end up with fractional parts that need rounding to a whole number — such as when you’re working out an average price, or dealing with random numbers . Thankfully, JavaScript’s Math object provides a number of ways to round numbers to an integer value.

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

Pro tip: you can also make this assignment in a single line using object destructuring :

Now we have these constants defined, let’s take a look at some of the methods for rounding numbers in JavaScript.

Rounding Numbers in JavaScript with Math.round

The first method we’ll look at is Math.round . This is the most straightforward option, and simply rounds any number with a decimal part to the nearest integer. It uses this rule: if a number is exactly halfway between two integers, it will be rounded up . For example, 2.5 will round up to 3.

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

Math.round() comes in handy if you want to round a number to the nearest integer value. For example, if you were calculating the average score over three tests, you’d add the three scores up and divide by three. This might not result in a whole number, so you’d use Math.round() to round it to the closest value:

Rounding Numbers with Math.floor

The next method we’ll look at is Math.floor . This always rounds a value down to the integer below (the name implies the number is being pushed down to the floor ):

A common use of Math.floor is when creating random integers . Rounding down ensures that the integer will start at zero and that each integer will have an equal chance of being returned. Starting at zero is generally useful, as arrays in JavaScript are zero-indexed, so rounding down will make sure that the first element in the array could be selected. The example below shows how a random element could be selected from an array using Math.floor :

Rounding down using Math.floor in the code above ensures that an index between 0 and 4 is returned, so every 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. The name comes from ceiling and is the opposite of floor , implying the value is going up . The method works in the same way as all the others. Just provide the number you want to round up as an argument:

But when would you need to round a number up? A common usage is if you need to work out how many containers you need for something. For example, say you have a music site that includes playlists, and each playlist has ten songs on it. If somebody uploads 82 songs, you need to work out how many playlists to create. This is done by dividing the number of songs by 10 (the number of songs on each playlist):

Using Math.round would round this down to 8 … but then we wouldn’t have a playlist for the last two songs! In cases like this, we always need to round up in order to have an extra container for any remainders:

Rounding Numbers with Math.trunc

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

At first glance, Math.trunc seems to be identical to Math.floor ; certainly the examples given so far all give the same results. These two methods behave differently, however, when a negative value is provided as an argument, as can be seen in the example below:

The difference occurs because, when a negative number is rounded down using Math.floor , it goes down to the next lowest integer, whereas truncating a negative value is the equivalent of rounding it up .

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

All of 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 figures?

Rounding Numbers To Decimal Places in JavaScript

We’ve already seen that Math.round will round numbers to the nearest integer. Unfortunately, the Math object doesn’t provide any methods to round numbers more accurately to a certain number of decimal places. Thankfully, the Number type has a couple of built-in methods that can do this. Let’s take a look at them.

Rounding to decimal places with Number.toFixed

This is a number method, which means that it’s called by the number itself. It rounds a decimal number to a given number of decimal places, which is provided as an argument:

One thing to note is that the value is returned as a string . You can get around this by wrapping the method call in the Number function, which will convert the result back into a number :

Something else 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 single dot to call the method:

You can’t call methods on integers using a single dot, because it isn’t clear if the dot is a method call operator or a decimal point. To get around this, you can either place the integer in parentheses or use two dots so that it’s clear that you’re calling a method rather than writing out a number literal with a decimal point:

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

A common use case for rounding to a set number of decimal places is when dealing with currency — for example, if you want to provide the price of something in US dollars to the nearest cent. Let’s say you had an ecommerce site that was running a promotion of 15% off anything in the shopping cart. The discounted price might need rounding before it’s displayed:

This can easily be fixed using Number.toFixed :

Note: for more on issues you might face with toFixed() , see Number().toFixed() Rounding Errors: Broken But Fixable .

Rounding numbers to decimal places with Number.toPrecision

The Number.toPrecision method works in a similar way to the Number.toFixed method, but it rounds numbers to a fixed number of significant figures .

If you need a quick reminder of significant figures, it basically means to only use the first non-zero digits. For large numbers, the final answer will also be padded out with zeroes as well. For example, the number 53,863 rounded to two significant figures will become 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 zeroes at the end to ensure the rounded value is a reasonable approximation to the original number.

You can also round decimals in a similar way. For example, 0.00000623978 will round to 0.0000062 to two significant figures 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 the number, providing the number of significant figures as an argument (remember that integers need to be placed in parentheses before calling a method on them):

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

As before, we can ensure that a number is returned by wrapping the method call in the Number function:

A common use for rounding to a given number of significant figures is when you’re dealing with large numbers and you’re not sure just how big they’re going to be. For example, 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, this depends how popular it is; you don’t want to round it to the nearest 100 if it only gets 8 likes, but if it gets thousands of likes then it seems silly to round it to the nearest 10. The solution is to round it to one significant figure:

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 stores numbers as 32-bit single precision binary values.

The problem with this is that some base 10 numbers can’t be accurately represented in base 2 . This doesn’t usually cause any problems, but it does cause some strange results such as this:

This is because 0.1 and 0.2 can’t be represented exactly in binary, and a slight error is made when adding them up.

The 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 represented exactly in binary as 0.101, so this will return the same value:

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

As you can see, it’s very close to 0.1, but very slightly higher. In most practical cases, this won’t cause any problems, but it can occasionally cause some strange behavior when you try to round some numbers:

This happens because the decimal 3.55 can’t be accurately represented in using 32-bits. We can use Math.fround to see how it’s actually represented:

As you can see, it’s actually represented by the floating point number 3.549999952316284, which rounds down to 3.5.

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

Which Methods Should I Use for Rounding Numbers?

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

If you simply want to round a number to the nearest integer , you can’t go far wrong with Math.round , but you should also consider using Math.floor or Math.ceil if you always want to round down or up, regardless of what the decimal part is. And consider using Math.trunc instead if you’re also planning on rounding negative numbers.

If you need to round to a given number of decimal places or significant figures , you’ll have to use Number.toFixed or Number.toPrecision . But be aware that these two methods are called by the 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 the Pen SitePoint Rounding by SitePoint ( @SitePoint ) on CodePen .

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

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

JavaScript: Novice to Ninja, 2nd Edition

Software Engineer at Polygon

Rounding and truncating numbers in JavaScript

Published: 2016.01.19 · 4 minutes read

Rounding and truncating is a bread and butter action for every single developer. It was covered during your first few math lessons in primary school. Hopefully you still remember how it works in the world of numbers.

5 or more? Raise the Score. 4 or less? Let it Rest.

Let’s use this knowledge and translate it to JavaScript using the built-in object called Math . As the name can suggests, it has a collection of properties and methods for mathematical operations on numbers. There is one small difference between Math and other built-in global objects. Math isn’t a constructor which means that all properties and methods that belong to it are static (meaning that they need to be called by using Math as an object).

Rounding vs Truncating

The difference between these two methods is minor but very important to understand. Both of them are methods of approximating a number by dropping decimal places. Rounding approximates a number using a nearby number at a given degree of accuracy. It can occur in two directions: up and down. Rounding up approximates a number towards positive infinity. Rounding down towards negative infinity. Truncating approximates without rounding. In other words, it “rounds” towards zero.

Hopefully you get the difference. It makes truncating rarely useful in precise calculations (although JavaScript probably isn’t a good choice at all if you need precise calculations) but you can come across a situation when it may be irreplaceable. Once example can be when needing to drop decimal places from a pixel value to avoid anti aliasing or weird pixel rounding which is completely different across browser engines.

Rounding numbers in Javascript

Rounding is straight forward. We can round to the nearest integer, round down or round up. JavaScript uses three methods to achieve this:

Rounding numbers with decimal precision requires a little bit of calculation and Math.round() . Optionally we can use the toFixed() method that belongs to the Number prototype. The output type of toFixed() is a string which needs to be passed to a top-level function called parseFloat() to return a number . Unfortunately this seems to be really slow.

Truncating numbers in Javascript

Math.trunc() simply removes all the fractional digits. It takes one argument which is a number. If the argument is a positive number it behaves exactly the same as Math.floor() . For negative numbers it does the same job as Math.ceil() .

It’s worth mentioning that the browser support for Math.trunc() isn’t great. It is part of new ES2015 (yeah, I prefer ES6 too) specification . Have a look at the browser support list:

Luckily there is a way to use this without ES6 support (thanks to Johny who suggested this solution in comments below). We can use bitwise operators to accomplish this task. Unfortunately there are some restriction as well. All bitwise operations work on signed 32-bit integers. Using them converts a float to an integer. In practice it means that we can safely work up to 2^31−1 ( 2 147 483 647 ) which is much less than Number.MAX_VALUE (1.7976931348623157e+308). This isn’t a great idea for monetary calculations either.

TLTR (too long to read)

I know, I know - time is money. Lets sum it up.

Did you like it? Please share it with your friends or get me a beer coffee. Thanks!

Widely-supported way of truncating is bitwise operator: -3.99 | 0 Although what's done here is not entirely clear. (bitwise shift operates on 32-bit numbers only so it returns those [integers]) You can write your own truncating polyfill using just that. function truncate(number){ return number|0; }

See which is faster for yourself here. :) http://jsperf.com/bitwise-v...

👆 you can use Markdown here

Fantastic tip. I may update this article with your tip if you don't mind. I won't forget about kudos for Johny :) Thanks again, really nice hint!

No problem. :)

Thanks a lot again. I just updated article and applied all your suggestions.

https://github.com/pawelgrz...

Your demo link is broken but my testing showed this |0 method to slightly faster than the rest (and the shortest to type). Math.trunc , Math.round etc are all about equal. toFixed(0) is exponentially slower (even before converting back to a number) and it also rounds kinda weird in some cases, like how (0.35).toFixed(1) = 0.3 yet (1.35).toFixed(1) = 1.4

I will fix the link. Thanks for pointing this one out and sharing your results!

Another thing that came to my mind is that toFixed is returning a string, not a number. So to get the number you would have to use parseInt (slow), or another method of getting fixed numbers (fast):

Math.round( 3.66666 * 100 ) / 100

Check the speeds: http://jsperf.com/tofixed-p...

Yeah I know what do you mean. I think you wanted to mention parseFloat() not parseInt() because in this example is all about floating points :-) Worth to add to article - definitely. Thank you so much for your input Johny. Can you give me your Twitter handle (if you have one). I'll update this article with all your advices later on today.

Rounding and truncating are really necessary for a developer to know and it's a good guide that you have created this article which can guide them on how to do it in Javascript.

Thank you very much! I'm glad that you found it useful.

toFixed is unreliable for rounding. Try this:

1.265.toFixed( 2 ) parseFloat( 1.265.toFixed( 2 ) )

// round to the nearest number taking into account the sign const round = number => Math.sign(number) * Math.round(Math.abs(number))

// rounds a number to its closer taking into account sign const round = number => { if (number === 0) return 0;

return number > 0 ? Math.round(number) : Math.sign(number) * Math.round(Math.abs(number)); }

That was a presentation!

Hi I have a problem with JavaScript

I have currency value 11.26 --I need always roundup ---12

If I have 12.56 I need roundup 13.

Thanks in advance.

This is exactly what Math.ceil() is doing.

Someone didn't read a word of this post :P

The Math.round(3.14159 * 100) / 100 // 3.14 rounding approach will not always be accurate. There are a lot of situations where it will round down values:

Math.round(Math.round(0.145 * 1000) / 10) / 100 // 0.15 Math.round(Math.round(1.005 * 1000) / 10) / 100 // 1.01

How can I change 9.26 to 9.27 using math.round ?

I am not sure if you understand the concept of rounding. It is not made for changing values but for rounding values.

`9.26 + 0.01`

Math.round rounds it to 9. If you want 9.27 then, You can do this by using parse float Method. Maybe: * parseFloat(9.264.toFixed(2)); //9.26 * parseFloat(9.266.toFixed(2)); //9.27

var truncated = number - number % 1;

var rounded = number + 6755399441055744.0 - 6755399441055744.0; // 2^51 + 2^52 This works for numbers with absolute value < 2 ^ 51.

var original=224.985 document.getElementById("demo").innerHTML = Math.round(original*100)/100; var original2=224.98499999 document.getElementById("demo2").innerHTML = Math.round(original2*100)/100;

output 224.99 224.98

in second case when no is 999999, it is not rounding to upper one What to be done to get second operation's value same as first one?

https://t.co/sO86kEe3uX?Vqkugn

https://t.co/yc6wKCq1xP?cjg...

Great article , thanks ! I wanted to ask though about this issue I encountered : somehow in Javascript : '28.99 - 28.70' is equal to => '0.28999999999999915' and not 0.29 ! How do I approach this to always get 0.29 ? 0.28999999999999915

You just became a victim of the "floating-point arithmetic precision". For people, something as obvious may not be that obvious for computers because of how they deal with number. Google this term to find out more about it. A classic example!

How to deal with it then? The answer isn't that simple, but it all comes down to avoid dealing with fractions if you can. In many e-commerce solutions, prices are represented like this…

By operating with numeric values using notations like this, all operations are done on the centAmmount first, and then the final result is divided by the fractionDigits . Hopefully, that helps.

Nice This is and i have used this in my javascript code

I am glad it helped you out :)

Leave a comment

Advertisements

TechOnTheNet Logo

clear filter

JS Loops/Conditionals

JS String Methods

JS Number Methods

down caret

JS Math Functions

Js array methods.

totn JavaScript

JavaScript: Math round() function

This JavaScript tutorial explains how to use the math function called round() with syntax and examples.

Description

In JavaScript, round() is a function that is used to return a number rounded to the nearest integer value. Because the round() function is a static function of the Math object, it must be invoked through the placeholder object called Math.

In JavaScript, the syntax for the round() function is:

Parameters or Arguments

The round() function returns a number rounded to the nearest integer. In other words, the number is rounded to 0 decimal places.

If the number is a negative value, the round() function rounds up towards zero which is different behavior than the round function in other languages.

Let's take a look at an example of how to use the round() function in JavaScript.

For example:

In this example, we have invoked the round() function using the Math class.

We have written the output of the round() function to the web browser console log , for demonstration purposes, to show what the round() function returns.

The following will be output to the web browser console log :

In this example, the first output to the console log returned 33 which is 32.65 rounded to the nearest integer.

The second output to the console log returned 8 which is 8.1 rounded to the nearest integer.

The third output to the console log returned -4 which is -4.2 rounded to the nearest integer. Notice that when dealing with negative numbers, the round() function rounds up towards zero and in this case, returned -4 and not -5. This behavior is different than the round functions in other languages.

previous

Home | About Us | Contact Us | Testimonials | Donate

While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy .

Copyright © 2003-2023 TechOnTheNet.com. All rights reserved.

Related Articles

JavaScript Math round() Method

The Javascript Math.round() method is used to round a number to its nearest integer. If the fractional part of the number is greater than or equal to .5, the argument is rounded to the next higher integer. If the fractional part of the number is less than .5, the argument is rounded to the next lower integer.

Parameters: This method accepts a single parameter as mentioned above and described below

Return Value: The Math.round() method returns the value of the given number rounded to the nearest integer.

Below is an example of the Math round() Method.

Example: To round off a number to its nearest integer. 

  Program 1: The Math.round() method itself rounds off a negative number when passed as a parameter to it. To round off a negative number to its nearest integer, the Math.round() method should be implemented in the following way: 

Program 2: Below program shows the result of the Math.round() method when the parameter has “.5” in decimal. 

We have a complete list of Javascript Math Objects methods, to check those please go through this Javascript Math Object Complete reference article.

Supported Browsers:

Please Login to comment...

Improve your Coding Skills with Practice

Start your coding journey now.

math.js

Function round #

Round a value towards the nearest integer. For matrices, the function is evaluated element wise.

Parameters #

Type | Description —- | ———–

ceil , fix , floor

Fork me on GitHub

Learn coding interactively.

Popular tutorials, popular examples, reference materials, learn python interactively, javascript math methods.

Related Topics

JavaScript Math floor()

JavaScript Math ceil()

JavaScript Math trunc()

JavaScript Math round()

In this tutorial, we will learn about the JavaScript Math.round() function with the help of examples.

The Math.round() function returns the number rounded to the nearest integer. That is, 3.87 is rounded to 4 and 3.45 is rounded to 3 .

Math.round() Syntax

The syntax of the Math.round() function is:

round() , being a static method, is called using the Math class name.

Math.round() Parameters

The Math.round() function takes in:

Return value from Math.round()

Math.round() returns the value of the number rounded to the nearest integer as follows:

Example: Using Math.round()

Note: Math.round() returns 0 for null rather than NaN .

Recommended readings:

Sorry about that.

Related Functions

JavaScript Library

JavaScript Math.fround()

Rounding a Number in JavaScript: Math.round()

IMAGES

  1. 34 Math Round Function In Javascript

    math rounding javascript

  2. 35 Javascript Round To Two Decimals

    math rounding javascript

  3. 8 Pics Javascript Math Floor Opposite And View

    math rounding javascript

  4. Javascript Round: How to Round The Value in JavaScript

    math rounding javascript

  5. Number Rounding in JavaScript

    math rounding javascript

  6. Java: Rounding Numbers (Math.round(), DecimalFormat & printf)

    math rounding javascript

VIDEO

  1. Help us code a weight converter!

  2. Round It Off

  3. LEETCODE 33 (JAVASCRIPT)

  4. Help at Home

  5. 27. ES6 While Loop and Do While Loop

  6. Round up Numbers in JavaScript

COMMENTS

  1. Math.round()

    The Math.round() static method returns the value of a number rounded to the nearest integer.

  2. JavaScript Math round() Method

    The Math.round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

  3. A Guide to Rounding Numbers in JavaScript

    The first method we'll look at is Math.round . This is the most straightforward option, and simply rounds any number with a decimal part to the

  4. Rounding and truncating numbers in JavaScript

    Rounding numbers in Javascript# · Math.round() - rounds to the nearest integer (if the fraction is 0.5 or greater - rounds up) · Math.floor() -

  5. JavaScript: Math round() function

    In JavaScript, round() is a function that is used to return a number rounded to the nearest integer value. Because the round() function is a static function of

  6. JavaScript Math.round( ) function

    JavaScript Math.round( ) function is used to round the number passed as a parameter to its nearest integer. Syntax: Math.round(value).

  7. JavaScript Math round() Method

    The Javascript Math.round() method is used to round a number to its nearest integer. If the fractional part of the number is greater than or

  8. Function round

    Round a value towards the nearest integer. For matrices, the function is evaluated element wise. Syntax #. math.round(

  9. JavaScript Math round()

    In this tutorial, we will learn about the JavaScript Math.round() function with the help of examples. The Math.round() function returns the number rounded

  10. Rounding in JavaScript

    Question: How do I round a number to n decimal places? Answer: To round a number in JavaScript, use the Math.round method: Math.round(X); // round X to an