最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论
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
发布评论

评论列表(0)

  1. 暂无评论