javascriptdecimalexponential

javascript how to express many-digit exponentials to 2 decimal places


I have a javascript program which spits out large arrays of numbers of the form '3.173538947635389377E+98', in the console, and have tried without luck to reduce them to something like '3.17E+98' for ease of comparison.

I Stringified the number, calculated the period and E locations, cut and diced until I had it of the string form '317.35E+96', with 96 as a multiple of 3. Then when I re-expressed as a number using Number(), it reverted to '3.173538947635389377E+98'. I could have left it as a string, but then would have to reconvert to Number later on. Is there a simple way of reducing the complexity? It is nearly impossible to inspect and see similar numbers etc, when the strings are so long. I guess the js people have their reasons, but am at my wits end.


Solution

  • You can use Intl.NumberFormat with engineering notation:

    const display = (n) => new Intl.NumberFormat('en', {
      notation: 'engineering',
      maximumFractionDigits: 2
    }).format(n);
    
    console.log(display(3.173538947635389377E+98));