BigDecimal的问题
来源:互联网 发布:天涯论坛和知乎 编辑:程序博客网 时间:2024/06/06 01:11
Java Doc解释
public BigDecimal(doubleval)Translatesa double into a BigDecimal which is the exact decimal representation of thedouble's binary floating-point value. The scale of the returned BigDecimal isthe smallest value such that (10scale × val) is an integer.
Notes:
The results of this constructor can besomewhat unpredictable. One might assume that writing new BigDecimal(0.1) inJava creates a BigDecimal which is exactly equal to 0.1 (an unscaledvalue of 1, with a scale of 1), but it is actually equal to0.1000000000000000055511151231257827021181583404541015625. This is because 0.1cannot be represented exactly as a double (or, for that matter, as a binaryfraction of any finite length). Thus, the value that is being passed in to theconstructor is not exactly equal to 0.1, appearances notwithstanding.
The String constructor, on the otherhand, is perfectly predictable: writing new BigDecimal("0.1") createsa BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, itis generally recommended that the String constructor be used in preference tothis one.
When a double must be used as a sourcefor a BigDecimal, note that this constructor provides an exact conversion; itdoes not give the same result as converting the double to a String using theDouble.toString(double) method and then using the BigDecimal(String)constructor. To get that result, use the static valueOf(double) method.
案例:
// float / double不能表示精确的小数。System.out.println(0.01 + 0.09); // 0.09999999999999999System.out.println(1.0 / 3 * 3);// BigDecimalBigDecimal bd1 = new BigDecimal(0.09);BigDecimal bd2 = new BigDecimal(0.01);System.out.println(bd1.add(bd2)); // 0.09999999999999999687749774324174723005853593349456787109375
BigDecimal bd3 = new BigDecimal("0.09");BigDecimal bd4 = new BigDecimal("0.01");System.out.println(bd3.add(bd4)); // 0.1
- 加减乘除的问题 - BigDecimal
- BigDecimal的比较问题
- BigDecimal的问题
- BigDecimal的问题
- BigDecimal的除法问题
- BigDecimal问题
- Double和BigDecimal计算比较compareTo不一致的问题[new BigDecimal(a).compareTo(new BigDecimal(b))]
- java.math.BigDecimal的精度问题
- 关于BigDecimal 的不精确计算问题
- java.math.BigDecimal的精度问题
- BigDecimal与科学计数法的问题
- BigDecimal(num).setScale ROUND_HALF_UP四舍五入的问题
- BigDecimal与科学计数法的问题
- java BigDecimal.setScale()的一些问题
- java.math.BigDecimal的精度问题
- java.math.BigDecimal的精度问题
- 解决double的精度问题-BigDecimal
- Java涉及算钱的问题BigDecimal
- UVA 122 Trees on the level(指针二叉树,层次遍历)
- hdu1213--How Many Tables
- LeetCode
- Spinner与Gallery
- ajax参数详解
- BigDecimal的问题
- 变量交换
- ubuntu安装jdk1.8
- ACM零起点2017-7-26(全排列问题)
- [C#]Application
- 基于微信红包插件的原理实现android任何APP自动发送评论(已开源)
- 安装office2010常见的提示错误解决办法
- background-position用法详解
- springmvc结合freemarker配置url访问的根路径