How to handle numbers bigger than machine representative number?

后端 未结 3 473
温柔的废话
温柔的废话 2021-01-21 07:55

Assuming now I\'m assigning ID number to my database, the database is huge(items more than machine representative number).

I\'m using Java, I know the biggest data type

相关标签:
3条回答
  • 2021-01-21 08:11

    You have specific classes for big numbers in Java, for example BigInteger.

    0 讨论(0)
  • 2021-01-21 08:16

    Java has a class java.math.BigInteger in its standard library that is meant to hold (and perform arithmetic on) arbitrarily large integers.

    But if you don't need to perform arithmetic, like in the case of a database ID, an ordinary String will work just as well.

    As to how you can get the number before converting it to a String, this depends on how you access the database. If you use the most standard option, JDBC, you will at a certain points have a java.sql.ResultSet. You can just call the ResultSet.getString(int columnIndex) or ResultSet.getString(String columnName) methods, even when the column in the database is a number, to get the String from it immediately without going through an intermediate int or long variable.

    0 讨论(0)
  • 2021-01-21 08:17

    Use java.math.BigInteger.

    BigInteger a = new BigInteger("123456789012345678901234567890");
    BigInteger b = new BigInteger("314159265");
    BigInteger c = a.add(b);
    System.out.println(c);
    

    Note (1) BigIntegers are immutable and (2) you have to use the methods add, subtract, etc. rather than +, -, etc.

    Also, BigInteger (and its floating-point analog, BigDecimal) is much lower slower than primitive types. BigInteger is fine for most cases, but avoid it if possible in performance sensitive code.

    0 讨论(0)
提交回复
热议问题