I'm using Node.js to print numbers to the console and want them to be easy to read. Because the numbers are displayed in columns, they should be the same length. Is there any easy way to do this before I start writing a monster function?
I've tried .toFixed()
and .padStart()
but they don't work well in all situations.
Part of the problem is converting a number to a string with .toString()
in JavaScript formats it with 'e' notation if the number is significantly small or large. I don't know how to prevent this. I went on the ECMAScript website to view the implementation for Number.prototype.toString()
and it's complicated.
Here are some examples of what I want:
Length: 8
Input Desired Output
12345678 => 12345678
1234 => 1234.000 // Works with .toFixed()
0 => 0.000000 // ^^
1234567890.0123 => 1.2345e9 // Doesn't work with .toFixed() or padStart()
0.00000000012345 => 1.234e-9 // ^^
1234567890123.123 => 1.234e12 // ^^
-123.4 => -123.400 // Works with .toFixed()
0.0123456789 => 0.012345 // Works with .slice()
e
notation, then how exactly do you want1234567890.0123
displayed in eight digits/characters …?Number(12334567890.0123).toString()
, I'll get something like1.234567e9
from JavaScript - which is 10 characters long. I could remove 2 digits before the e but there's a few edge cases.