1

I have the following in Kotlin to convert a BigInteger down to ordinary integer

    val bigIntDiv = bigIntVal?.div(BigInteger.valueOf(429496))
    val resultInt = bigIntDiv?.toInt() //This line converts the big Interger down to regular integer

How can I achieve this same conversion in javascript.

I am using the BigNumber.js library https://github.com/MikeMcl/bignumber.js/ and I can't figure out a way to get back the regular integer from the BigNumber

This is what I currently have with the BigNumber.js library:

let bigIntVal = new BigNumber("5ACDBB4CC493D909F423D779C2C55E7381DFAE6547DCEFE5712F", 16)

Now I want to get back the regular integer as shown from the Kotlin's equivalent code above?

Such that:

let regularInteger = bigIntVal.toInt(); //would be the same value as returned from the Kotlin's end?

For a sample bignumber

5.09632306328228901945340839021510597564609217303391975753746718457743300101444483767019949e

I have tried using the BigNumber.js library the following:

let initial = new BigNumber("5.09632306328228901945340839021510597564609217303391975753746718457743300101444483767019949e",16);
let workingVal = initial.toNumber(); //This gives 5.096323063282289e+70, which is not what I want

When I wrote similar code in kotlin, kotlin gave me what I want

    val resultInt = initial?.toInt() //Kotlin gave me -1879845894 which is great to work with.

So, how can I achieve same thing with the BigNumber.js library Thanks.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
mekings
  • 361
  • 3
  • 17
  • 1
    I think what you are looking for is `.toNumber()` which means in your case `bigIntVal.toNumber()`, see https://mikemcl.github.io/bignumber.js/#toN for more information – Simperfy Jan 16 '21 at 06:10
  • I find it hard to understand your problem, where did the value `"5ACDBB4CC493D909F423D779C2C55E7381DFAE6547DCEFE5712F"` came from? – Simperfy Jan 16 '21 at 06:25
  • It's unclear to me what behavior your going for. First off, Kotlin BigInteger is only for integers, but JS BigNumber is more comparable to Kotlin BigDecimal. Why not use JS built-in [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) type? Secondly, Kotlin toInt() just returns the low-order 32-bits as a two-complement signed integer. Is that the behavior you want. – President James K. Polk Jan 16 '21 at 15:03

1 Answers1

1

Here's a quick example of converting bigNumber to primitive int:

let bigIntVal = new BigNumber("5ACDBB4CC493D909F423D779C2C55E7381DFAE6547DCEFE5712F", 16)
let bigIntValToInt = bigIntVal.toNumber()

// double check
console.log(typeof bigIntVal);
console.log(typeof bigIntValToInt);
Simperfy
  • 117
  • 10