比double更精确的数值数据类型? [英] more precise numeric datatype than double?

查看:623
本文介绍了比double更精确的数值数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否存在比 double c>更精确地存储十进制数的数据类型?

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

推荐答案

是的,使用 java.math.BigDecimal 类。它可以非常精确地表示数字。

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

如果你只需要大整数,你可以使用 java.math.BigInteger

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

他们两者都扩展 java.math.Number

如果需要,您甚至可以使用现有的双打:

You can even use your existing doubles if you need:

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

您可以使用JDBC从数据库中获取BigDecimal值:

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");
}

不幸的是,由于Java不支持运算符重载,因此无法定期使用常见数学运算的符号,如C#和十进制类型。

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

这篇关于比double更精确的数值数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆