104

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?

4
  • Javascript doesn't have a parseLong because it doesn't have a long. (Some old-timer may be able to tell you a story about why Javascript never got a long.) Commented Mar 27, 2011 at 14:58
  • So it's not possible to do arithmetic with longs in javascript?? Commented Mar 27, 2011 at 15:02
  • can you give a code example of what you want to do? Commented Mar 27, 2011 at 15:12
  • @Russ - your answer below explains it all. thx Commented Mar 27, 2011 at 15:21

2 Answers 2

136

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@CharlieS You use a library like javascript-bignum (github.com/jtobey/javascript-bignum) or BigInt.js (leemon.com/crypto/BigInt.html) that provides support for large numbers.
be careful with zero to left side
10

BigInt("1274836528318476135")

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.