100

I have a millisecond timestamp that I need to convert from a string to long. JavaScript has a parseInt but not a parseLong. So how can I do this?

To expand on my question slightly: given that apparently JavaScript doesn't have a long type, how can I do simple arithmetic with longs that are initially expressed as strings? E.g subtract one from the other to get a time delta?

VLAZ
  • 22,934
  • 9
  • 44
  • 60
Richard H
  • 36,221
  • 37
  • 107
  • 137

2 Answers2

123

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

Russ Cam
  • 121,250
  • 30
  • 197
  • 258
  • 1
    So, if I wanted to parse the string `"71157133118211271"` to a number/long in Javascript, how would I go about that? Split it into 16-digit strings, parse each of them separately, and concatenate them together? – Charlie Schliesser Aug 29 '13 at 22:37
  • 2
    @CharlieS You use a library like javascript-bignum (https://github.com/jtobey/javascript-bignum) or BigInt.js (http://www.leemon.com/crypto/BigInt.html) that provides support for large numbers. – Russ Cam Apr 23 '14 at 20:23
  • be careful with zero to left side – Cazs Oct 01 '20 at 07:09
7

BigInt("1274836528318476135")

Jamey
  • 4,100
  • 2
  • 23
  • 19