I am dealing with floating point numbers and need to display them on an widget on webpage which has limited width. I mostly use tofixed(2) for all my floating point number. But there are certain cases where there are numbers like: 0.0000000365468
, only 0.00
are printed because of tofixed(2). I cannot permanently set it to tofixed(8) as normal cases will take too much space then.
Is there any inbuilt functionality in javascript/jquery where I can automatically get round the number to the nearest meaningful number (in above case: 0.00000003
or 0.00000004
to be precise)?
You could take the log10 and use a threshold for taking the value.
function f(x) {
return x.toFixed(Math.log10(x) < -2 ? 8 : 2);
}
console.log(f(0.0000000365468));
console.log(f(0.000000365468));
console.log(f(0.00000365468));
console.log(f(0.0000365468));
console.log(f(0.000365468));
console.log(f(0.00365468));
console.log(f(0.0365468));
console.log(f(12.34));
A dynamic approach
function f(x) {
return x.toFixed(Math.max(-Math.log10(x) + 1, 2));
}
console.log(f(0.0000000365468));
console.log(f(0.000000365468));
console.log(f(0.00000365468));
console.log(f(0.0000365468));
console.log(f(0.000365468));
console.log(f(0.00365468));
console.log(f(0.0365468));
console.log(f(12.34));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With