Automatically round floating point number with variable number of zeros after decimal point to first non zero digit [duplicate]

  • A+
Category:Languages

This question already has an answer here:

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)?

Please help.
Thanks

 


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));

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: