比double更精确的数值数据类型? [英] more precise numeric datatype than double?
问题描述
Java中是否存在比 double $ c> 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屋!