There’s a couple different ways to round to two decimal places in Javascript. Which one you use will depend on your situation.
Table of Contents
Use Math.round
The best way to do this is using Math.round
, especially if you still need a number on the other end to do math on.
Here is the most accurate and correct way to do it:
function roundToTwoDecimalPlaces(num) {
return Math.round((num + Number.EPSILON) * 100) / 100;
}
const pi = 3.14159265359;
const roundedPi = roundToTwoDecimalPlaces(pi);
console.log(roundedPi);
// -> 3.14
console.log(typeof roundedPi);
// -> Number
JavaScriptWhat is Number.EPSILON?
Number.EPSILON
is a static data property of the Number object in JavaScript, which represents the difference between 1 and the smallest floating point number greater than 1.
Why are we adding it to the number?
It prevents errors when rounding small numbers. How / why? I read the documentation but still have no idea. Here, see if you can figure it out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON.
Use toFixed
This appears to be the easiest way at a glance, but there’s a caveat: the number you round will be returned as a string, not a float. So, if you need to do any further math on the number, you won’t be able to until you convert it back.
Here’s how you use it:
const num1 = 2.455;
console.log(num1.toFixed(2));
// -> 2.46
const num2= 2.4;
console.log(num2.toFixed(2));
// -> 2.40
JavaScriptWarning! The result of this function is a string
not a float
!
What if I still need a number?
You can convert it back to a number by using the parseFloat
function built in to Javascript:
const num = 2.455;
const roundedNum = num.toFixed(2);
console.log(roundedNum);
// -> 2.46
console.log(typeof roundedNum);
// -> string
// Convert it back to a floating point
const roundedNumFloat = parseFloat(roundedNum);
console.log(roundedNumFloat);
// -> 2.46
console.log(typeof roundedNumFloat);
// -> number
JavaScriptHere’s a function using this method that you can copy/paste:
function roundToTwoDecimalPlaces(num) {
return parseFloat(num.toFixed(2))
}
JavaScriptJohn is a professional software engineer who has been solving problems with code for 15+ years. He has experience with full stack web development, container orchestration, mobile development, DevOps, Windows and Linux kernel development, cybersecurity, and reverse engineering. In his spare time, he’s researching the potential business applications of AI.