Jazib - 9 days ago 6

Javascript Question

I want to round off a float in Javascript, with (at least) 2 significant figures.

For example, with following desired results:

`roundOff(0.000000001124) // 0.0000000011 or 1.1e-9 (both acceptable)`

roundOff(1.423421) // 1.42

roundOff(0.00053245) // 0.00053

roundOff(422.243224) // 422.24

roundOff(422.0000000123) // 422.00

I know I can use logarithm and round to do something similar as mentioned here, but it rounds off even larger numbers, like

`-123.0 -> -100`

Any clever Javascript based solution?

Answer

If I understand correctly, you want a function that returns two significant figures for numbers with an absolute value less than 1, or two decimal places for numbers with an absolute value greater than 1.

I still don't understand why you think `0.000000001124`

should be rounded to `0.0000000012`

. Did you mean to write `0.0000000011`

instead?

If so, this function should do what you want:

```
function roundOff(n) {
return parseFloat(n.toExponential(Math.max(1,2+Math.log10(Math.abs(n)))));
}
```

```
var a = new Array(0.000000001124, 1.423421, 0.00053245, 422.243224,
422.0000000123, 123, -123);
for (i=0; i<7; i++) console.log(roundOff(a[i]));
```

**Output:**

```
1.1e-9
1.42
0.00053
422.24
422
123
-123
```