java BigDecimal的使用
简单使用
public class Solution { public static void main(String... arg) { /** * 创建 */ //string BigDecimal bigDecimal = new BigDecimal("1.010"); //int bigDecimal = new BigDecimal(1); //long bigDecimal = new BigDecimal(1L); //double, 不能用这个方法, 想double var = 0.1 二进制实际存储的值为0.10000000000000000555111... bigDecimal = new BigDecimal(0.1f); //科学计数法 bigDecimal = new BigDecimal("0.1E5"); /** * 运算 */ BigDecimal bdtemp = new BigDecimal(1); //乘法 bigDecimal.multiply(bdtemp); //💇🏻 bdtemp.subtract(bdtemp); //加法 bdtemp.add(bdtemp); //除法 bdtemp.divide(bdtemp); /** * 除法存在精度丢失, 报错 * 1、设置精度 * 2、取余数 */ //设置精度 bigDecimal = new BigDecimal(10); MathContext mathContext = new MathContext(2, RoundingMode.CEILING); bigDecimal.divide(new BigDecimal(3), mathContext); //取余数, 0 整数部分,1小数部分 BigDecimal[] dr = bigDecimal.divideAndRemainder(new BigDecimal(3)); /** * 转换 */ bigDecimal.intValue(); bigDecimal.longValue(); bigDecimal.floatValue(); bigDecimal.doubleValue(); /** * 四舍五入 * RoundingMode.HALF_UP 四舍五入 * RoundingMode.DOWN 舍弃 * */ bigDecimal.setScale(2, RoundingMode.CEILING); /** * 格式化 * DecimalFormat * 0, 阿拉伯数字,如果不存在则显示0 * #, 阿拉伯数字,如果不存在不显示0 * ., 小数分隔符或货币小数分隔符 * ,, 分组分隔符 * E, 数字 分隔科学计数法中的尾数和指数。在前缀或后缀中无需加引号。 * %, 前缀或后缀 乘以 100 并显示为百分数 * -, 负号 */ DecimalFormat df = new DecimalFormat("#.##"); df = new DecimalFormat("00.####E0"); df.format(bigDecimal); //舍入模式 df.setRoundingMode(RoundingMode.CEILING); /** * compare * 不能使用equal,equal还比较scale(), 0.1 和0.10不等 */ bigDecimal.compareTo(bdtemp); /** * matchContext 精度 */ mathContext = new MathContext(2, RoundingMode.CEILING); } }