Artiga - 6 months ago 31

Javascript Question

I know that Math.round rounds the number to nearest integer.

What I need is to round a number within specific range. For e.g.

If num=4.50 and range=0.1

so number in +- 0.1 of 4.5 should be rounded to 4.5

i.e. mathrangeRound(4.44) =4.5 and MathrangeRound(4.6) =4.5

Any help with this is appreciated.

Thank you.

Answer

You can try something like this:

```
function aggr(num, pre, base){
return Math.abs(base - num) <= pre ? base : num
}
console.log(aggr(4.44, 0.1, 4.5))
console.log(aggr(4.6, 0.1,4.5))
console.log(aggr(4.8, 0.1,4.5))
console.log(aggr(4.8, 0.3,4.5))
```