DEV Community

Cover image for Converting big strings of number into Number
Delyce Twizeyimana
Delyce Twizeyimana

Posted on

Converting big strings of number into Number

there are several ways used to convert a string to number such as

  1. Number(str)
  2. parseInt(str, 10)
  3. (+str)
  4. (str * 1) and so on.. where str is a number string like str = "123"
str = "123"
'123'
console.log(+str)
Output: 123

Enter fullscreen mode Exit fullscreen mode

However, the above ways don't work when you have a very big string

let str = "6145390195186705543"
console.log(Number(str))
Output: 6145390195186705000

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

}
Enter fullscreen mode Exit fullscreen mode

Read more about BigInt on : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

Top comments (0)