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.
Number() object and
let price = 8.333333333333; let priceRounded = Number((price).toFixed(2)); console.log('Original Price: ' + price); console.log('Price Rounded: ' + priceRounded);
Original Price: 8.333333333333 Price Rounded: 8.33
Here is what developer.mozilla.org says this about
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
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.
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:
For more information about toFixed(), see: