Reputation: 381
Input Number : 3266.528
deciaml Point: 1
output for decimal point (1) : 3266.5
output for decimal point (2) : 3266.53
output for decimal point (3) : 3266.528
output for decimal point (4) : 3266.5280
How to round numbers based on decimal point given as above. Based on input number and decimal point, I would like to get the number rounded as above
Upvotes: 1
Views: 9729
Reputation: 851
use .toFixed() on the number. The parameter you give will determine the number of digits to return after the decimal point.
let num = 3266.5390
console.log(num.toFixed(2)) // answer will be 3266.54
console.log(num.toFixed(3)) // answer will be 3266.539
Upvotes: 1
Reputation: 889
A popular way in javascript is simply the following :
const num = 3266.528;
const result = Math.round(num * 100) / 100;
where the 100 will round to 2 decimal places, 1000 for 3 places, etc.. You can parameterize and make use of Math.pow(10, idx)
if you'd like e.g.
const round = (n, dec) => (Math.round(n * Math.pow(10, dec)) / Math.pow(10, dec));
Upvotes: 1