James - 7 months ago 29

Javascript Question

I need a function which takes a calculated value (can range from very small to very large) and rounds it to a number of decimal places for display. The number of decimal places should depend on the magnitude of the input and so I can't just use something like

`.toFixed(n)`

`n`

I came up with the following, but have the feeling there's a much better way of doing this:

`function format_output(output) {`

if (output > 10000) {

output = output.toFixed(0);

} else {

if (output > 100 && output < 10000) {

output = output.toFixed(1);

} else {

if (output>1 && output <100) {

output = output.toFixed(3);

} else {

// repeat as necessary

}

return output;

}

Thanks!

Answer

For your requirement you should look into scientific notation

```
output.toExponential();
```

If you dont want to use scientific notation try this instead:

```
function format_output(output) {
var n = Math.log(output) / Math.LN10;
var x = 4-n;
if(x<0)
x=0;
output = output.toFixed(x);
return output;
}
```