在Java中处理大数值的精度问题, 可以考虑使用 BigDecimal或BigInteger.
环境如下:
OS: Windows XP Service Pack 2
JDK: 1.5.0_10
BigDecimal bc = new BigDecimal("15323121312.052");
BigDecimal bc2 = new BigDecimal("13123234.12");
Assert.assertEquals("15336244546.172", bc.add(bc2).toString());
Assert.assertEquals("15309998077.932", bc.subtract(bc2).toString());
Assert.assertEquals("201088908427219973.61424", bc.multiply(bc2).toString());
// java.lang.ArithmeticException
Assert.assertEquals("1167.63300661529309057240", bc.divide(bc2).toString());
运算
|
结果的首选标度
|
加
|
max(addend.scale(), augend.scale())
|
减
|
max(minuend.scale(), subtrahend.scale())
|
乘
|
multiplier.scale() + multiplicand.scale()
|
除
|
dividend.scale() - divisor.scale()
|
从某种意义上说, BigDecimal可以处理任意位数的数值, 查阅Source便可知:
BigDecimal实际上内部维护一个数组
/**
* The magnitude of this BigInteger, in <i>big-endian</i> order: the
* zeroth element of this array is the most-significant int of the
* magnitude. The magnitude must be "minimal" in that the most-significant
* int (<tt>mag[0]</tt>) must be non-zero. This is necessary to
* ensure that there is exactly one representation for each BigInteger
* value. Note that this implies that the BigInteger zero has a
* zero-length mag array.
*/
int[] mag;
// 避免小数无限循环, 指定精度位数和RoundingMode
bc.divide(bc2, 3, RoundingMode.HALF_UP);
分享到:
相关推荐
dive into python3 (中文版)dive into python3 (中文版)dive into python3 (中文版)
Deep Dive into Android IPC-Binder Framework 深入Android IPB/Binder 框架
Dive Into HTML5 中文版 Dive Into HTML5 中文版 Dive Into HTML5 中文版
《深入Python 3》(Dive Into Python 3,英,)的的电子版,HTML格式
Dive into Python 中文版 Dive into Python 中文版
Dive into Python3 很不错哦,有中文的就更好了。
diveintopython源代码 很全
dive into python_代码_教程 dive into python_代码_教程
diveintopython3 书中源代码,非常好的一本书,极力推介,本人从中学到很多写代码的技巧
dive into python的中文版,很不错的python教程
dive into python英文原版,Dive Into Python 3 covers Python 3 and its differences from Python 2. Compared to Dive Into Python, it’s about 20% revised and 80% new material. The book is now complete, ...
Dive Into Python 3 中文版.pdf 如果需要英文的也可以联系我
《Dive Into Python》,带完整目录书签,经典文档,供参考。
2015-Dive into Python-中文版, python研究,很好的书
Dive Into Python 3 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Dive Into Python 2 中文版 深入学习Python,需要学习Python基础知识
Didyoureadtheoriginal“DiveIntoPython”?Didyoubuyit onpaper?(Ifso,thanks!)AreyoureadytotaketheplungeintoPython3?…Ifso,readon.(Ifnoneofthat istrue,you’dbebetteroffstartingatthebeginning.) Python3...
Dive Into Python 3 examples,随书示例代码包。
Dive Into Python 3 中文版