1

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()
3
  • if you convert to int you could use developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . hope it helps
    – Paulquappe
    Commented Feb 27, 2018 at 10:35
  • If you don’t want the e notation, then how exactly do you want 1234567890.0123 displayed in eight digits/characters …?
    – C3roe
    Commented Feb 27, 2018 at 10:41
  • I'm fine with the e notation for the output. It's just if I call Number(12334567890.0123).toString(), I'll get something like 1.234567e9 from JavaScript - which is 10 characters long. I could remove 2 digits before the e but there's a few edge cases.
    – Josh Grant
    Commented Feb 28, 2018 at 8:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.