4

I was trying to figure out why one of our clients on Facebook was having issues and I traced it to the number 10150141932135203 turning into 10150141932135204 giving us rather unexpected results.

$ node
> 10150141932135203
10150141932135204
> 10150141932135204
10150141932135204
> 10150141932135205
10150141932135204
> 10150141932135206
10150141932135206
> 10150141932135207
10150141932135208
> 10150141932135208
10150141932135208
> 10150141932135209
10150141932135208
> 10150141932135210
10150141932135210

How can I deal with integer numbers of this size?

Kit Sunde
  • 35,972
  • 25
  • 125
  • 179

1 Answers1

4

If the numbers are bigger than what the IEEE 754 spec allows (253), they will lose precision as your examples demonstrate.

You could use a Binary Coded Decimal library for JavaScript, e.g. BCMathJs.

This, of course, is only applicable if you need to perform arithmetic on the numbers. If not, keep them as strings.

alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    That library will become crazy popular now then when every single Facebook application will be unable to reliably talk to Facebook UIDs of that size. – Kit Sunde Mar 06 '12 at 07:14
  • 2
    @KitSunde If you are not performing arithmetic, just keep them as strings. – alex Mar 06 '12 at 07:16
  • You also have libraries purely for integers of any size which may be faster eg https://github.com/silentmatt/javascript-biginteger – James Westgate Mar 06 '12 at 07:18
  • 1
    @alex Seems like the way to go. I also had to get HTML data attributes via `$("body").attr("data-page-id")` rather than `$("body").data("page-id")` because of this. – Kit Sunde Mar 06 '12 at 08:45
  • @KitSunde Yeah, the helpful *turn into a native type from guessing* sometimes isn't too helpful with `data()`. – alex Mar 06 '12 at 10:39