How to Output Numbers With Leading Zeros in JavaScript

How to output numbers with leading zeros in JavaScript?

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.

You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:

function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}

Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.

function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}

If you care about negative numbers you'll have to strip the - and read it.

How do I retain leading zeroes in an Integer/Number in JavaScript?

You can't have a number with leading zeroes in Javascript, because, as Randy Casburn said, they don't have any value. You have to convert it to a string and use String.padStart() to pad the string with zeroes. parseInt will work with leading zeroes. For example:

(294).toString().padStart(6, "0") --> "000294"

parseInt("000294") --> 294

How can I pad a value with leading zeros?

Since ECMAScript 2017 we have padStart:

const padded = (.1 + "").padStart(6, "0");
console.log(`-${padded}`);

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

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"

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

console.log(String(5).padStart(2, '0'));

Keep trailing or leading zeroes on number

No. A number stores no information about the representation it was entered as, or parsed from. It only relates to its mathematical value. Perhaps reconsider using a string after all.


If i had to guess, it would be that much of the confusion comes from the thought, that numbers, and their textual representations would either be the same thing, or at least tightly coupled, with some kind of bidirectional binding between them. This is not the case.

The representations like 0.1 and 0.10, which you enter in code, are only used to generate a number. They are convenient names, for what you intend to produce, not the resulting value. In this case, they are names for the same number. It has a lot of other aliases, like 0.100, 1e-1, or 10e-2. In the actual value, there is no contained information, about what or where it came from. The conversion is a one-way street.

When displaying a number as text, by default (Number.prototype.toString), javascript uses an algorithm to construct one of the possible representations from a number. This can only use what's available, the number value, also meaning it will produce the same results for two same numbers. This implies, that 0.1 and 0.10 will produce the same result.

Concerning the number1 value, javascript uses IEEE754-2019 float642. When source code is being evaluated3, and a number literal is encountered, the engine will convert the mathematical value the literal represents to a 64bit value, according to IEEE754-2019. This means any information about the original representation in code is lost4.

There is another problem, which is somewhat unrelated to the main topic. Javascript used to have an octal notation, with a prefix of "0". This means, that 003 is being parsed as an octal, and would throw in strict-mode. Similarly, 010 === 8 (or an error in strict-mode), see Why JavaScript treats a number as octal if it has a leading zero

In conclusion, when trying to keep information about some representation for a number (including leading or trailing zeroes, whether it was written as decimal, hexadecimal, and so on), a number is not a good choice. For how to achieve some specific representation other than the default, which doesn't need access to the originally entered text (e.g. pad to some amount of digits), there are many other questions/articles, some of which were already linked.


[1]: Javascript also has BigInt, but while it uses a different format, the reasoning is completely analogous.

[2]: This is a simplification. Engines are allowed to use other formats internally (and do, e.g. to save space/time), as long as they are guaranteed to behave like an IEEE754-2019 float64 in any regard, when observed from javascript.

[3]: E.g. V8 would convert to bytecode earlier than evaluation, already exchanging the literal. The only relevant thing is, that the information is lost, before we could do anything with it.

[4]: Javascript gives the ability to operate on code itself (e.g. Function.prototype.toString), which i will not discuss here much. Parsing the code yourself, and storing the representation, is an option, but has nothing to do with how number works (you would be operating on code, a string). Also, i don't immediately see any sane reason to do so, over alternatives.

How to output numbers with leading zeros in JavaScript?

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.

You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:

function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}

Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.

function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}

If you care about negative numbers you'll have to strip the - and read it.

Number with leading zeroes gets changed in JavaScript

JavaScript thinks it is an octal value (because of the leading zero and the lack of digits greater than 7). The decimal value of octal 0011110416605 is 1226972549. Example:

> var value = 010; //10 in octal
> console.log(value);
> 8 //is 8 in decimal

Use a string instead:

removeFromCart("0011110416605")

Increment a number without getting rid of leading zeroes

// I suppose databasevalue is a string
var databasevalue = "0125";

// coerce the previous variable as a number and add 1
var incrementvalue = (+databasevalue) + 1;

// insert leading zeroes with a negative slice
incrementvalue = ("0000" + incrementvalue).slice(-4); // -> result: "0126"


Related Topics



Leave a reply



Submit