Search code examples
javastringstring-comparison

How to Convert a String formatted Big number to Number?


Suppose

String num = "14151841515451321511151545"

I want to convert this to

number = 14151841515451321511151545

I need to convert to Number to compare with another String formatted number like

String num2 = "7845141651641616111"

How to do it? Is there any String method to compare with long string formatted number?

I tried Long.parseLong(), but It is giving NumberFormatException.


Solution

  • Strings compare character "strings" and not numbers, as their name implies.

    Also "7845141651641616111" is too large for an integer.

    Try:

    String num = "14151841515451321511151545"
    BigInteger number = new BigInteger(num);
    String num2 = "7845141651641616111"
    BigInteger number2 = new BigInteger(num2);
    

    See https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/math/BigInteger.html for comaperTo(...), equals(...), etc.