Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 306
Kashyap Kotak Avatar asked Feb 04 '23 23:02

Kashyap Kotak


1 Answers

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));
like image 108
Nina Scholz Avatar answered Feb 06 '23 14:02

Nina Scholz