• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Math Related / 3 Ways To Round a Number to 2 Decimal Places in JavaScript

3 Ways To Round a Number to 2 Decimal Places in JavaScript

How To Round a Number to 2 Decimal Places in JavaScript

Rounding a number to a specific decimal place in JavaScript can be accomplished using the .toFixed() method. This method rounds a number to the number of decimal places specified, and returns the result as a string.

Here is an example of using the .toFixed() method to round a number to 2 decimal places:

var number = 3.14159;
var roundedNumber = number.toFixed(2);
console.log(roundedNumber); // Output: "3.14"

In this example, the variable number is set to the value of 3.14159, and the .toFixed(2) method is used to round this number to 2 decimal places. The result, 3.14, is then assigned to the variable roundedNumber, which is then logged to the console.

It’s important to note that the .toFixed() method returns a string, not a number. If you need to work with the rounded number as a number, you can use the parseFloat() method to convert the string back to a number:

var number = 3.14159;
var roundedNumber = parseFloat(number.toFixed(2));
console.log(roundedNumber); // Output: 3.14
console.log(typeof roundedNumber); // Output: "number"

Another way to round a number to 2 decimal places, is by using the Math.round() method. This method rounds a number to the nearest integer. We can use this method and divide the number by 100 and then multiply by 100.

var number = 3.14159;
var roundedNumber = Math.round(number * 100) / 100;
console.log(roundedNumber); // Output: 3.14

In this example, we first multiply the number by 100, then round it to the nearest integer, and finally divide it by 100. This will result in a number rounded to 2 decimal places.

Math Related

Related Snippets:

  • Format a number to a fixed number of decimal places
  • Circumference Calculator
  • Check if the given value is a number
  • Round a number to a specified amount of digits

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers