javascript - How to round number based on decimal point provided in angular 7 - Stack Overflow

Input Number : 3266.528deciaml Point: 1output for decimal point (1) : 3266.5output for decimal point

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
Add a ment  | 

2 Answers 2

Reset to default 2

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));

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信