JavaScript round a number to 2 decimal places (with examples)

JavaScript round a number to 2 decimal places (with examples)

What do you understand with the question that “Round a number to x decimal places?” The answer is just round off the given decimal number to x decimal places. for example, round the 5.678 to 2 decimal places. the result will be 5.68.

Introduction

Javascript(JS) is a scripting programming language. It is one of the important techniques used for front-end web development. Nowadays nearly all websites are built using JS. Because JS helps to interact with users. It stores the actions of users while using the website. JS makes websites more engaging and interactive. It also supports object-oriented programming language. for example, when you like any post on Instagram, simultaneously like button colours changes, this is possible because of Javascript. That’s why JS has now a wide use in almost every area.

Syntax structure in JavaScript

Unlike other general-purpose languages, JavaScript also has its syntax, statements, variables, functions, and semantics format.

Statements are instructions given for the execution of a task, in any programming language. JS statements comprise variables, comments, values, expressions, and semicolons (optional).

All the operations and syntax are simple to learn like other languages. A variable must be declared before any assignment in JS. To declare a variable you can either use “var” or “let”.

var a;
let b //semicolon is  optional.
a = 2;
b = 3;
console.log("print sum of a and b:",a+b)Code language: JavaScript (javascript)

Output

print sum of a and b: 5Code language: Shell Session (shell)

comments in JS are similar to CPP and C languages.

//This is a single-line comment. similar to c++.
/*This is for multi-line comments.
  similar to c.
  */Code language: JavaScript (javascript)

To print anything in Javascript, you can use “console.log()”.

console.log("Welcome to Codedamn!");Code language: JavaScript (javascript)

Output

Welcome to Codedamn!

All possible ways to round off a number in JavaScript

As I mentioned above, JS also has syntax, variables, and functions, unlike other languages. So, to round off a number to a given number of decimal places, there are multiple ways in JS. Let’s deep dive into this method one by one.

Use Inbuilt function(toFixed())

toFixed(x) is an inbuilt function in JS. It is used to round off a decimal number to specific decimal places. This function only takes x as input. x is the number up to which the given number will be rounded. It is used as a number.toFixed(x).

var a = 5.678948;
let b = 10.257683;
let result1 = a.toFixed();
let result2 = b.toFixed(2);
console.log(result1);
console.log(result2);
Code language: JavaScript (javascript)

Output

6
10.26Code language: Shell Session (shell)

You can see that if you specify ‘x’ into the function then it rounds the given number to zero decimal places. but when you give ‘x=2’ into the function then, it rounds the number to 2 decimal places.

NOTE – toFixed(x) function – Always first typecast the given decimal number(float value) into a string. Then round the number to x decimal places. Hence, the data type of result will be a string. You can verify by using the typeof function.

var a = 5.678948;
let b = 10.257683;
let result1 = a.Tofixed();
let result2 = b.toFixed(2);
console.log(result1)
console.log(result2)
console.log(typeof result2)Code language: JavaScript (javascript)

Output

6
10.26
stringCode language: Shell Session (shell)

By using the Math. round() function

This is one more possible method that one can use to round a given number to specific decimal places. for round-off to 2 decimal places you need to use 100.

var a = 5.678948;
let b = 10.257683;
let c = 6.6456583;
let result1 = Math.round(a*100)/100;
let result2 = Math.round(b*10)/10;
let result3 = Math.round(x*1000)/1000;
console.log(result1)
console.log(result2)
console.log(typeof result2)Code language: JavaScript (javascript)

Output

5.68
10.3
6.646Code language: Shell Session (shell)

Let’s explore some situations where the above functions fail to give the right answer. for example, this function returns 1.25 instead of 1.26 for the number 1.255. similarly, it will return 1 for the number 1.005 instead of 1.01. Hence, There is some scope for changes in the “Math. round()”. Here I have listed some methods that you can use to modify the function.

Use Number.EPSILON

var a = 1.005;
var b = 1.255;
let result1 = Math.round((a + Number.EPSILON)*100)/100;
let result2 = Math.round((b + Number.EPSILON)*100)/100;
console.log(result1)
console.log(result2)Code language: JavaScript (javascript)

Output

1.01
1.26Code language: CSS (css)

Using a constructor to round off a number

As you know javascript also supports object-oriented programming. Hence you can take benefit of that also. There is one more approach to round off a number is using a constructor – Intl.NumberFormat(). This constructor format the number as currency according to the given locale or region. If locale is not mentioned it will format the number only by adding commas. You can use this constructor with or without a new keyword.

//without locale
console.log(new Intl.NumberFormat().format(125698));

//with locale - US and Japanese
console.log(Intl.NumberFormat('en-US').format(125698));
console.log(Intl.NumberFormat('de-DE').format(125698));Code language: JavaScript (javascript)

Output

125,698
125,698
125.698Code language: JavaScript (javascript)

So use it to round off a number to x decimal places. for that, you need to specify the x in the code. you can customise the locale and x according to your choice.

//Intl.NumberFormat(locale,x).format(number)
//x is how many significant digits you want after rounding off the number.
//IN for international

console.log(Intl.NumberFormat('en-IN',{ maximumSignificantDigits: 3 }).format(125698));Code language: JavaScript (javascript)

Output

1,26,000Code language: JavaScript (javascript)

You can even try this approach by changing the rounding-off conditions. As the given constructor has many functions and properties you can try. for example, try and check what will be the result if you use minimumSignificantDigits or minimumFractionDigits or maximumFractionDigits instead of maximumSignificantDigits.

let temp = Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
  maximumSignificantDigits: 2,
});
console.log(temp.format(1144.2945)); 
console.log(temp.format(114425)); 
console.log(temp.format(134.22)); 
Code language: JavaScript (javascript)

Output

1,1001,10,000130Code language: JavaScript (javascript)

User-defined function

These are functions defined by the users themselves. here I have shown some examples below:

Example of a user-defined function by using an exponent. It will round the number up and down. “e+2”, 2 is for 2 decimal places.

var a = 1.005;
let b = 2.68678;
function roundNum(number){
   return +(Math.round(number + "e+2") + "e-2");
}
console.log(roundNum(a))
console.log(roundNum(b))Code language: JavaScript (javascript)

Output

1.01
2.69Code language: Shell Session (shell)

Conclusion

As I have shown some of the methods above, you can use one of the approaches to round – off a decimal number in javascript. You can also define your user-defined function to solve the above problem.

At last one more extra point or a hint for you is the use of Math.floor() and Math.ceil() functions. by using these two functions you can round down or round up a number.

So finally, you have learned different approaches to round off a number up to given decimal places. Try to implement this on your own. Come out with some more techniques to solve this same problem. All the best.

Sharing is caring

Did you like what Srishti Kumari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far