Search code examples
javascriptconcatenation

Javascript: concatenating "000" to a number and string


I have these epochs:

1586998726 and "1586998726"

I need to turn both to:

1586998726000 and "1586998726000"

Can't really figure out. Help appreciated.


Solution

  • If you have

    var epochInteger = 1586998726;
    var epochString = "1586998726";
    

    You can do:

    For the number

    epochInteger * 1000 === 1586998726000;
    

    For the string

    epochString + "000" === "1586998726000";
    

    To do conversions between them

    epochInteger.toString() === epochString;
    Number(epochString) === epochInteger;
    

    But note that these conversions work in both cases

    epochString.toString() === epochString;
    Number(epochInteger) === epochInteger;
    

    So in general you could use something like

    var modifiedEpochInteger = Number(epochAnyType) * 1000;
    var modifiedEpochString = modifiedEpochInteger.toString();
    

    and you'd get the result in both types, no matter where you started!