let x = 5.15; // A number with decimals let y = 5; // A number without decimals
You can see its high-frequency appearing in relation to things like length, weight and money as examples.
That implies that you will have to prepare the numbers in accordance with a particular format. This may be deceptively challenging.
Let’s say you are working with money, using an integer followed by two decimal places is the transparent approach to prepare money for display.
You can either round a number to move the decimal point (for multiplication) or round a number and move the decimal place back (division).
The question here is: Which approach is correct?
Method #1: Using the Number.toFixed() method
An integer is sent into the Number.toFixed() function, which returns the result as a string. The full number will range from 0 to 20.
Running the code:
let x = 3.87612763261; let res = x.toFixed(2); console.log(res);
Method #2: Using the Math.round() Function
To make sure the number is rounded correctly, we take it and add a tiny amount, Number.EPSILON.
After rounding to only the two digits following the decimal point, we multiply the number by 100.
The number is then divided by 100 to a maximum precision of two decimal places.
Running the code:
var numb= 81276325.219843773; var rounded = Math.round((numb + Number.EPSILON) * 100) / 100; console.log(rounded);
Despite being an improvement over.toFixed(), this approach is still not the best option and will incorrectly round to 1.005 as well.
Method #3: Using Double Rounding: The toPrecision() Method
Add the decimals to acquire the desired length if they are not given. The advantage of this approach is that it eliminates mistakes that single rounding introduces during intermediate computations.
var numObj = 7.12839728; console.log(numObj.toPrecision());// Returns 7.12839728 console.log(numObj.toPrecision(2));//Returns 7.1 console.log(numObj.toPrecision(3));//Returns 7.13 console.log(numObj.toPrecision(4));//Returns 7.128