How would I convert Int 623527832412487691 to Int 623527832412487691n without the number changing value
I don't want Int 623527832412487691 to turn to Int 623527832412487700 as apparently JavaScript does some conversion to BigInt
I have
let string = 623527832412487691
console.log(string)
and it prints 623527832412487700
JavaScript has a limitation on the precision of integer values due to the way it represents numbers using the double-precision floating-point format. The number you provided exceeds the maximum safe integer in JavaScript (
Number.MAX_SAFE_INTEGER), that is, 9007199254740991. Once you go beyond this limit, you start losing precision.To handle large integers accurately in JavaScript without losing precision, you can use the BigInt data type, introduced in ECMAScript 2020. However, when initializing a BigInt directly from a literal, JavaScript will still use floating-point arithmetic if the number is too large.
To handle your specific case, you can convert your number to a BigInt using the BigInt constructor.
Here, 623527832412487691n explicitly represents a BigInt without any loss of precision. This way, you won't face the issue of JavaScript converting the number to a floating-point representation.
If you have the number as a string, you can explicitly convert it to a BigInt by doing the following:
Updates based on further comments
Update 1:
While retrieving a value from a MySQL database column that stores numbers as strings, you can ensure that it remains a string by explicitly converting it to a string after retrieving it. You can use either
String()or.toString()functions for this.With explicit type conversions, you avoid automatic conversion to a number in JavaScript.