EagL - 9 months ago 41

Javascript Question

I'm trying to round a number to the nearest specified decimal.

I want it to round to the decimals .11, .22, .33, .44, .55, .66, .77, .88 but not .99. Instead .99 should be 1.

For example:

`1.14 -> 1.11`

56.75 ->56.77

34.234 -> 34.22

1.01 -> 1 (not 1.11)

The problem is not rounding to a specific number of decimals, it's rounding to the nearest of one of these decimals.

I've tried

`(Math.round(parseFloat(number)*10)/9).toFixed(2);`

And I've gotten the decimals I've wanted mostly, except for the 1 rounding to 1.11 and .55 for example became .56 which I don't want. Plus it was more than it was supposed to be, obviously because I multiplied by 10 and then divided by just 9.

Answer Source

I suggest to separate the integer part and the fractional part.

If the fractional part is close to factor 9, then return the integer part plus one, otherwise the integer part plus the corrected fractional part.

```
function getRight(v) {
var i = Math.floor(v),
f = Math.round((v - i) / 0.11);
return i + (f === 9 || f * 0.11);
}
console.log([1.14, 56.75, 34.234, 1.01].map(getRight));
```