TMB
TMB

Reputation: 4703

How come I can't add 1 to a large number in javascript

var i = 20040115102010000;

i++;

returns 20040115102010000;

Do I have to use a Big Number Library?

What is the standard solution in JavaScript for handling big numbers (BigNum)?

This number was already in floating point format and I moved the decimal place to the left three times. Also, notice, it is a date. Would it behoove me to convert this number to a date format first? Will I find it easier to increment in milliseconds in the Date() object?

Upvotes: 0

Views: 344

Answers (3)

Priya Shelke
Priya Shelke

Reputation: 76

This will increase your number by 1. e.g if digits = 12346456783211345; digits = (BigInt(digits)) + BigInt(1);

After using BigInt it will be look like 12346456783211346

This solution worked for me.

Upvotes: 1

kzh
kzh

Reputation: 20608

JavaScript now has a bigint type.

Upvotes: 0

kennebec
kennebec

Reputation: 104830

You can't use a Date that big in javascript, without making a bigDay library to handle your bignums.

/*

from 'https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date':

The JavaScript date is measured in milliseconds since midnight 01 January, 1970 UTC. A day holds 86,400,000 milliseconds. The JavaScript Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC. */

var firstday=new Date(1970,0,1),lastday=new Date(1969,11,31);

firstday.setDate(firstday.getDate()-100000000);

lastday.setDate(lastday.getDate()+100000000);

firstday.toUTCString()+'; timestamp: '+firstday.getTime()+'\n'+
lastday.toUTCString()+'; timestamp: '+lastday.getTime();

/* returned value: (largest and smallest Dates in JS)

Tue, 20 Apr -271821 04:00:00 GMT; timestamp: -8639999985600000

Fri, 12 Sep 275760 04:00:00 GMT; timestamp: 8639999928000000 */

Upvotes: 2

Related Questions