Skip to content
Advertisement

How to output numbers with leading zeros in JavaScript? (satoshi format)

Is there a way to prepend leading zeros and a dot to numbers so that it results in a string of fixed length?

For example: 1 becomes “0.00000001 BTC”. 498 becomes “0.00000498 BTC”.

Advertisement

Answer

use / to divide, then toFixed(). For example:

const number = 10;
console.log((number / 100000000).toFixed(8));

You can put it in a function:

const toZerosNumber = number => (number / 100000000).toFixed(8);

And use it with your examples:

toZerosNumber(498); // Output: "0.00000498"
toZerosNumber(1); // Output: "0.00000001"
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement