more precise numeric datatype than double?

后端 未结 6 1957
南方客
南方客 2021-02-07 14:02

Is there a datatype in Java that stores a decimal number more precisely than a double?

相关标签:
6条回答
  • 2021-02-07 14:20

    Yes, use java.math.BigDecimal class. It can represent numbers with great precision.

    If you just need huge integers, you can use java.math.BigInteger instead.

    They both extend java.math.Number.

    You can even use your existing doubles if you need:

    double d = 67.67;
    BigDecimal bd = new BigDecimal(d);
    

    And you can get BigDecimal values out of databases with JDBC:

    ResultSet rs = st.executeQuery();
    while(rs.next()) {
        BigDecimal bd = rs.getBigDecimal("column_with_number");
    }
    

    Unfortunately, since Java does not support operator overloading, you can't use regular symbols for common mathematical operations like you would in C# and the decimal type.

    You will need to write code like this:

    BigDecimal d1 = new BigDecimal(67.67);
    BigDecimal d2 = new BigDecimal(67.68);
    BidDecimal d3 = d1.add(d2); // d1 + d2 is invalid
    
    0 讨论(0)
  • 2021-02-07 14:21

    you can use a BigDecimal

    To calculate with with BigDeciamls this class provides special methods that are used instead of the standard operators e.g. + - * / ... that you from int, double and so on...

    0 讨论(0)
  • 2021-02-07 14:25

    Depends on the range of your input. Many times, you can just use int or long. For money, just store the integer number of pennies. int will handle up to $20,000,000.00 which is large enough for my bank account. long goes far higher.

    If your range is suitable, using long is much faster and cleaner than using BigDecimal

    0 讨论(0)
  • 2021-02-07 14:30

    Yes, you can use an arbitrary precision class such as BigDecimal.

    0 讨论(0)
  • 2021-02-07 14:32

    Yes: the java.math.BigDecimal class.

    0 讨论(0)
  • 2021-02-07 14:33

    Use BigDecimal it offers much better precision

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