tl;dr
Use String
, not double
文字。
new BigDecimal( "2.78" ) // Pass "2.78" not 2.78
.multiply(
new BigDecimal( "0.008853" ) // Pass "0.008853" not 0.008853
)
.toString()
0.02461134
不要传递浮点类型
要点是BigDecimal类是为了避免固有的不准确性在发现浮点技术。浮点类型,例如float
/Float
and double
/Double
牺牲准确性来换取执行速度。相比之下,BigDecimal
速度慢但准确。
你的代码:
new BigDecimal( 0.76135 )
new BigDecimal( 1.1345 )
new BigDecimal( 0.008853 )
…正在通过double
原始文字。在编译过程中,您输入的文本0.76135
被解析为一个数字,具体来说是一个double
(64 位浮点值)。此时,您已经引入了这种类型固有的不准确性。换句话说,double
产生于0.76135
可能不再完全是0.76135
.
让我们转储你的BigDecimal
实例化后立即实例化。
System.out.println( new BigDecimal( 0.76135 ) ); // Passing a `double` primitive.
System.out.println( new BigDecimal( 1.1345 ) );
System.out.println( new BigDecimal( 0.008853 ) );
0.7613499999999999712230192017159424722194671630859375
1.13450000000000006394884621840901672840118408203125
0.0088529999999999997584154698415659368038177490234375
所以,通过创建double
数字值,您调用了浮点技术,并引入了不准确性。
使用字符串
解决方案?使用字符串,避免double
完全键入。
放一些这些输入用双引号引起来, and voilà.
System.out.println( new BigDecimal( "0.76135" ) ); // Passing a `String` object.
System.out.println( new BigDecimal( "1.1345" ) );
System.out.println( new BigDecimal( "0.008853" ) );
0.76135
1.1345
0.008853
Example
你所期望的2.78 * 0.008853 = 0.0246
。我们来试试吧。
BigDecimal x = new BigDecimal( "2.78" );
BigDecimal y = new BigDecimal( "0.008853" );
BigDecimal z = x.multiply( y );
System.out.println( x + " * " + y + " = " + z );
2.78 * 0.008853 = 0.02461134
接下来你应该学习舍入和截断BigDecimal
。 Stack Overflow 上已经介绍过很多次了。