James James - 9 months ago 35
Javascript Question

Dynamically round number to n decimal places depending on magnitude

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

is unknown.

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;



For your requirement you should look into scientific notation


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;
    output = output.toFixed(x);
    return output;