Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Number.toString returns "incorrect" hexadecimal value

In order to utilize a third party API, I have to convert the ID number to a hexadecimal. I converted the ID with https://www.rapidtables.com/convert/number/decimal-to-hex.html and got 711DD21A11FA9223FEB43849FF1F3569DC024DCE000000000000150000000001. This works when I use it with the API.

My understanding is that you can perform the same conversion with JS with Number().toString(16). However, when I use that function I get 711dd21a11fa9400000000000000000000000000000000000000000000000000.

The latter value does not work with the API. Any insight into why the JS function returns a different value?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Screenshot of public converter and JS script

>Solution :

Your number is too big for JavaScript.

The Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in JavaScript.

I advise you to use the BigInt data type.

BigInt is a primitive wrapper object used to represent and manipulate primitive bigint values – which are too large to be represented by the number primitive.

Exampe:

// Your ID in decimal
const decimalNumber = BigInt(10000000000000000);

// Your ID in hex
const hexNumber = decimalNumber.toString(16);

// Conversion to a string, since BigInt is not displayed in the console for demonstration.
console.log(decimalNumber.toString());

console.log(hexNumber);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading