there are several ways used to convert a string to number such as
- Number(str)
- parseInt(str, 10)
- (+str)
- (str * 1) and so on.. where str is a number string like str = "123"
str = "123"
'123'
console.log(+str)
Output: 123
However, the above ways don't work when you have a very big string
let str = "6145390195186705543"
console.log(Number(str))
Output: 6145390195186705000
Here We get unexpected output, because we are dealing with a big string number.
Walk around:
BigInt values represent numeric values which are too large to be represented by the number primitive.
Using BigInt to convert a big string number
let str = "6145390195186705543"
console.log(BigInt(str))
6145390195186705543n
And here we get the expected output with n appended at the end
In case you want to do some mathematical operations on your output, yeah, it's possible e.g output + 1n
6145390195186705543n + 1n
6145390195186705544n
You can check how I used this to solve a problem on leetcode:
Question link: https://leetcode.com/problems/plus-one/
My Solution
var plusOne = function(digits) {
let fin=[]
let comb =singleValue(digits)
comb = BigInt(comb)
comb = comb +1n
let arr = comb.toString().split('')
for(let i=0; i<arr.length; i++){
fin.push(Number(arr[i]))
}
return fin
};
function singleValue(arr){
let str = ""
for(let i=0; i<arr.length; i++){
str +=arr[i]
}
return str
}
Read more about BigInt on : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
Top comments (0)