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
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
Share Improve this question asked Apr 29, 2021 at 9:57 NishanthNishanth 3811 gold badge6 silver badges24 bronze badges 1- Take a look at the decimal pipe: angular.io/api/mon/DecimalPipe – Andreas Louv Commented Apr 29, 2021 at 9:59
2 Answers
Reset to default 2A 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));
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745109507a4611761.html
评论列表(0条)