Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Converting string into number, result in a different number

Converting string into number, result in a different number

Problem

When I try to convert a bigint passed from php, into a integer in nodejs, the result is always different, I couldn't figure out what's wrong with it.

> var a = parseInt('135601920000000040', 10);
undefined
> a
135601920000000030
> var a = parseFloat('135601920000000040');
undefined
> a
135601920000000030
> var n = Number('135601920000000040');
undefined
> n
135601920000000030

Not only node.js, it also happen to js interpreter in Firefox

Problem courtesy of: Leric

Solution

The Number type in javascript is represented as double precision floating point, so, it a value passed to parseInt, parseFloat etc is more than 9007199254740992 (ECMAScirpt Numbers specification) it is rouned to fit the Number type.

Solution courtesy of: Just_Mad

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Converting string into number, result in a different number

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×