Kala J - 11 months ago 27

Javascript Question

I have a float number like 137.57667565656 but I would like to round it such that there are only two trailing digits after the decimal point like the new float number will be 137.58.

I tried this so far:

`(Math.round((value*100)/100)).toFixed(2).toString();`

But unfortunately, it rounds my value to 137.00. It adds the decimals places as zeroes, why?

How can I achieve the above?

Answer

What did you expect?

```
(value*100)/100
```

simply returns the original value of *value*, so

```
Math.round((value*100)/100))
```

is identical to:

```
Math.round(value)
```

you then have:

```
Math.round(value).toFixed(2).toString();
```

so *value* is rounded to an integer, *toFixed* will add two decimal places and return a string so the *toString* part is redundant. If you wish to round *value* to four decimal places, then:

```
value.toFixed(4)
```

will do the job:

```
var x = 137.57667565656;
console.log(x.toFixed(4)); // 137.5767
```

If you want to round it to 2 places but present it as 4, then:

```
Number(x.toFixed(2)).toFixed(4) // 137.5800
```