1

I am new in javascript,so please forgive if it is worthless question. However,I have big decimal number which I need to show without any exponential notation.

For e.g. var a = 0.00000000005545545468864654 should be shown as 0.00000000005545545468864654 instead of 5.545545468864654e-11

Can anyone help me regarding it.

I have tried the below approach

var a = 0.00000000005545545468864654
Number.parseFloat(a).toFixed(30)

where 30 is the count of decimal places.But this approach is not working and giving result "0.000000000055455454688646537182" which is not "0.00000000005545545468864654"

Ankur Sharma
  • 45
  • 3
  • 10

3 Answers3

1

Why 30 decimal places when you have only 26.

var a = 0.00000000005545545468864654
console.log(Number.parseFloat(a).toFixed(26));
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
0

You can use a function if you want:

function toFixed(x) {
  if (Math.abs(x) < 1.0) {
    var e = parseInt(x.toString().split('e-')[1]);
    if (e) {
        x *= Math.pow(10,e-1);
        x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
    }
  } else {
    var e = parseInt(x.toString().split('+')[1]);
    if (e > 20) {
        e -= 20;
        x /= Math.pow(10,e);
        x += (new Array(e+1)).join('0');
    }
  }
  return x;
}

const num = 0.00000000005545545468864654;

console.log(toFixed(num))
wobsoriano
  • 12,348
  • 24
  • 92
  • 162
0

Precision is an intrinsic issue of binary representation of decimal numbers. There are techniques and precision setters which will work well only up to a certain precision. Then limits are hit. It is not an issue it's possible to solve but workarounds include:

  • converting every digit to int and keeping them separate, print with a toString, define custom operations
  • multiplying chunks of decimal digits before performing operations and then dividing back, which may or may not work and may or may not scale. This includes converting numbers to ints by multiplying by a power of 10.

And of course libraries have been made to address this concern. Check BigNumbers based on decimaljs

Attersson
  • 4,755
  • 1
  • 15
  • 29