JavaScript: How to format a number to two decimal places

Let’s say we need to present a number on a web page so that it is always a floating point number with two decimal places. This is for cases where absolute precision is not needed but we want to always present a number output in a uniform way.

Here is an example of how to format a long floating point number to two decimal places using JavaScripts Number() object and toFixed()  function:

let price = 8.333333333333;
let priceRounded = Number((price).toFixed(2));
console.log('Original Price: ' + price);
console.log('Price Rounded: ' + priceRounded);

which yields:

Original Price: 8.333333333333
Price Rounded: 8.33

Here is what developer.mozilla.org says this about Number():

The Number JavaScript object is a wrapper object allowing you to work with numerical values. A Number object is created using the Number() constructor.

The primary uses of the Number object are:

If the argument cannot be converted into a number, it returns NaN.
In a non-constructor context (i.e., without the new operator), Number can be used to perform a type conversion.

w3schools says this about Number():

The Number() function converts the object argument to a number that represents the object’s value.

If the value cannot be converted to a legal number, NaN is returned.

Note: If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.

 

The numObj.toFixed(digits) function basically takes in a number and returns a string with the number of decimal places specified in the parenthesis.

 

For more information about Number, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
https://www.w3schools.com/jsref/jsref_Number.asp

For more information about toFixed(), see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
https://www.w3schools.com/jsref/jsref_tofixed.asp