BigDecimal的精确计算及工具类

news/2024/5/18 6:40:59

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

 

System.out.println(new BigDecimal("10000000000").toString());
System.out.println( new BigDecimal("100.000").toString());
System.out.println( new BigDecimal("100.000").stripTrailingZeros().toString());
System.out.println( new BigDecimal("100.000").stripTrailingZeros().toPlainString());

输出:

10000000000
100.000
1E+2
100

 

BigDecimal是处理高精度的浮点数运算的常用的一个类
当需要将BigDecimal中保存的浮点数值打印出来,特别是在页面上显示的时候,就有可能遇到预想之外的科学技术法表示的问题。
一般直接使用 BigDecimal.toString()方法即可以完成浮点数的打印。如:
System.out.println( new BigDecimal("10000000000").toString());
但是,toString()方法输出的字符串并不能保证不是科学计数法。
不过在日常的使用中,用toString()方法输出的就是普通的数字字符串而非科学计数法。直接这么写:
System.out.println( new BigDecimal("100.000").toString());
程序的输出即为:  100.000
如果我们希望去除末尾多余的0,那么我们应该这么写:
System.out.println( new BigDecimal("100.000").stripTrailingZeros().toString());
其中,stripTrailingZeros()函数就是用于去除末尾多余的0的,但是此时程序的输出为: 1E+2
是科学计数法,可能并不是我们想要的。
解决的方法很简单,如果想要避免输出科学计数法的字符串,我们要用toPlainString()函数代替toString()。如:
System.out.println( new BigDecimal("100.000").stripTrailingZeros().toPlainString());
此时程序的输出就为 100


如果想要输出的是100.00 强制保留2位小数,则需要DecimalFormat。

System.out.println(new DecimalFormat("0.00").format(new BigDecimal("100.000")));

输出:

100.00

DecimalFormat中的“0” “#”意义:

Symbol    Location   Localized?  Meaning    
0              Number    Yes            Digit    
#             Number     Yes            Digit, zero shows as absent

简单说,0的没有的补零,#的没有就缺席没有(不显示)。

new java.text.DecimalFormat("#.###").format(3.0)  
new java.text.DecimalFormat("0.000").format(3.0)

输出的结果却为:  3 和 3.000 。

 

BigDecimalUtils工具类

package com.imddy.tweb.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimalUtils {
	
	// 默认精度10, 应该是2,4, 特别是做金额计算,到分和到毫
	public static final int DEFAULT_SCALE = 10;
	public static final int DEFAULT_DIV_SCALE = 10;
	
	// 默认的格式化字符样式 “#。00”  还可以是像“#。0000”
	public static final String DEFAULT_FORMAT_STR = "#.00";
	
	// 加法
	public static BigDecimal add(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2);
	}

	// 减法
	public static BigDecimal sub(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2);
	}
	
	// 乘法
	public static BigDecimal mul(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2);
	}
	
	// 除法,默认精度
	public static BigDecimal div(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, DEFAULT_DIV_SCALE, BigDecimal.ROUND_HALF_UP);
	}
	
	// 对一个double截取指定的长度,利用除以1实现
	public static BigDecimal round(double v1, int scale) {
		if (scale < 0) {
			new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal("1");
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP);
	}

	// 除法,自定义精度
	public static BigDecimal div(double v1, double v2, int scale) {
		if (scale < 0) {
			new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP);
	}
	

	// 比较2个double值,相等返回0,大于返回1,小于返回-1
	public static int compareTo(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.compareTo(b2);
	}
	
	// 判断2个double的值相等这里要改,相等返回true,否则返回false
	public static boolean valuesEquals(double v1, double v2) {
		boolean result;
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        int resultInt = b1.compareTo(b2);
        if (resultInt == 0) {
        	result = true;
        } else {
        	result = false;
        }
        return result;
	}
	
	// 判断2个double的值,v1大于v2返回true,否则返回false
	public static boolean valuesGreater(double v1, double v2) {
		boolean result;
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        int resultInt = b1.compareTo(b2);
        if (resultInt > 0) {
        	result = true;
        } else {
        	result = false;
        }
        return result;
	}
	
	// 判断2个double的值,v1小于v2返回true,否则返回false
	public static boolean valuesLess(double v1, double v2) {
		boolean result;
		BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        int resultInt = b1.compareTo(b2);
        if (resultInt < 0) {
        	result = true;
        } else {
        	result = false;
        }
        return result;
	}
	
	// DecimalFormat格式化,使用默认的格式样式
	public static String format(Object object) {
		return new DecimalFormat(DEFAULT_FORMAT_STR).format(object);
	}
	
	// DecimalFormat格式化,使用传入的字符串格式样式
	public static String format(Object object, String formatStr) {
		return new DecimalFormat(formatStr).format(object);
	}

	
	
	
	public static void main(String[] args) {
		
		double a = 178.63;
		double b = 3.251;
		System.out.println(BigDecimalUtils.add(a, b));
		System.out.println(BigDecimalUtils.sub(a, b));
		System.out.println(BigDecimalUtils.mul(a, b));
		System.out.println(BigDecimalUtils.div(a, b));
		System.out.println(BigDecimalUtils.div(a, b, 5));
		// 不能以double来构建BigDecimal,只能由string来构建BigDecimal
		System.out.println(new BigDecimal(Double.valueOf(a)));
		System.out.println(new BigDecimal(Double.toString(a)));
		System.out.println(new BigDecimal(Double.toString(a)).toString());
		System.out.println(BigDecimalUtils.compareTo(a, b));
		System.out.println(BigDecimalUtils.compareTo(b, a));
		System.out.println(BigDecimalUtils.valuesEquals(0.002, 0.0020));
		System.out.println(BigDecimalUtils.valuesGreater(a, b));
		System.out.println(BigDecimalUtils.valuesLess(a, b));
		
		//
		System.out.println( BigDecimalUtils.mul(0.03, 0.0002).stripTrailingZeros().toPlainString() );
		System.out.println( BigDecimalUtils.mul(0.03, 0.0002).stripTrailingZeros() );
		System.out.println( BigDecimalUtils.mul(0.03, 0.0002).stripTrailingZeros().toString() );
		System.out.println("----------");
		
		System.out.println(new BigDecimal("10000000000").toString());
		System.out.println( new BigDecimal("100.000").toString());
		System.out.println( new BigDecimal("100.000").stripTrailingZeros().toString());
		System.out.println( new BigDecimal("100.000").stripTrailingZeros().toPlainString());
		
		System.out.println(new DecimalFormat("0.00").format(new BigDecimal("100.000")));
		System.out.println(new DecimalFormat("#.00").format(new BigDecimal("100.000")));

	}

}

 

转载于:https://my.oschina.net/lenglingx/blog/1618599


http://www.niftyadmin.cn/n/4582766.html

相关文章

error: No resource identifier found for attribute ‘footerColor’ in package

异常提示: 使用自定义控件&#xff0c;引用包名应该是AndroidManifest.xml中所定义的包路径&#xff0c;并非src下.java文件所指向的包&#xff0c;这个容易犯错&#xff01; 否者Android studio 中的xml布局界面&#xff0c;运行后会提示以下错误: error: No resource identif…

Eclipse 调试时,出现错误闪退,但是控制台没有打印错误信息

解决途径&#xff1a; 可以监视一下 ThreadGroup这个类的uncaughtException这个方法 贴上代码给予参考 /** Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements. See the NOTICE file distributed with* this work for ad…

区块链中密钥对的生成原理

bitcoin中的密钥综述 关于bitcon中使用的椭圆曲线加密体制的一些事实&#xff1a; 私钥长度 32bytes 公钥长度 64bytes (未压缩形式) 或者 32bytes&#xff08;压缩形式&#xff09; 1byte&#xff08;前缀&#xff09; 椭圆曲线C是secp256k1曲线椭圆曲线加密体制基于模运算 在…

SSH hibernate 分页的几种实现方式

转载请注明出处~&#xff01;&#xff01; 第一种: DetachedCriteria Criteria 形式 SuppressWarnings({ "unchecked", "rawtypes" })public PageModel getPageModel(final PageModel pageModel, final DetachedCriteria _criteria, Class entityType)…

textarea文本域自适应高度

-----------------html <div><textarea autoHeight"true">textarea</textarea></div> 复制代码-----------------js $.fn.autoHeight function(){function autoHeight(elem){elem.style.height auto;elem.scrollTop 0; //防抖动elem.styl…

优秀Android博客大全,整理了国内外大神博客/Github地址,是学习Android进阶的首选[转]

[转]国内外优秀Android博客大全&#xff0c;覆盖了国内外大神博客地址&#xff0c;Github地址&#xff0c;是学习Android进阶的首选国内&#xff1a; 昵称Github博客介绍邓凡平 http://blog.csdn.net/innost阿拉神农魏祝林 http://blog.csdn.net/android_tutor Trineahttps://…

Bitmap 图片格式并用 C++ 读写 Bitmap

转自 Bitmap 图片格式并用 C 读写 Bitmap 1、Bitmap 图片格式 每部分的具体内容就不展开了。要说的有两点&#xff1a; &#xff08;1&#xff09;调色板不是必须的&#xff0c;可有可无&#xff0c;有没有调色板可以通过位图文件头的 bfOffBits 是否等于位图文件头加上位图信息…

Android Studio多渠道打包和代码混淆教程 【亲测可用】

from : http://www.tuicool.com/articles/mQZNvey 时间 2015-11-18 10:13:14 极客头条原文 http://coolshell.info/blog/2015/03/android-studio-prefrence.html主题 Gradle Android Studio什么是Gradle Gradle是一种依赖管理工具&#xff0c;基于Groovy语言&#xff0c;面向J…