javascriptleading-zerozerofill

How can I pad a value with leading zeros?


How can I pad a value with leading zeroes in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?

Note: By padding the value I mean it in the database sense of the word (where a 6-digit padded representation of the number 5 would be "000005").


Solution

  • Since ECMAScript 2017 we have padStart:

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

    Before ECMAScript 2017

    With toLocaleString:

    var n=-0.1;
    var res = n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false});
    console.log(res);