使用BigDecimal去掉小数点后无用的0

 更新时间:2021年08月14日 10:40:52   作者:采坑先锋  
这篇文章主要介绍了使用BigDecimal去掉小数点后无用的0操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

如题:BigDecimal去掉小数点后无用的0

比如:数据库存储的是Decimal(5,2)类型保留两位数。

如果展示数据5.00,5.10等字样感觉很不爽,如何做呢?

只战术5和5.1

解决:BigDecimal,有方法解决stripTrailingZeros()

看源码:

/**
     * Returns a string representation of this {@code BigDecimal}
     * without an exponent field.  For values with a positive scale,
     * the number of digits to the right of the decimal point is used
     * to indicate scale.  For values with a zero or negative scale,
     * the resulting string is generated as if the value were
     * converted to a numerically equal value with zero scale and as
     * if all the trailing zeros of the zero scale value were present
     * in the result.
     *
     * The entire string is prefixed by a minus sign character '-'
     * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than
     * zero. No sign character is prefixed if the unscaled value is
     * zero or positive.
     *
     * Note that if the result of this method is passed to the
     * {@linkplain #BigDecimal(String) string constructor}, only the
     * numerical value of this {@code BigDecimal} will necessarily be
     * recovered; the representation of the new {@code BigDecimal}
     * may have a different scale.  In particular, if this
     * {@code BigDecimal} has a negative scale, the string resulting
     * from this method will have a scale of zero when processed by
     * the string constructor.
     *
     * (This method behaves analogously to the {@code toString}
     * method in 1.4 and earlier releases.)
     *
     * @return a string representation of this {@code BigDecimal}
     * without an exponent field.
     * @since 1.5
     * @see #toString()
     * @see #toEngineeringString()
     */
    public String toPlainString() {
        if(scale==0) {
            if(intCompact!=INFLATED) {
                return Long.toString(intCompact);
            } else {
                return intVal.toString();
            }
        }
        if(this.scale<0) { // No decimal point
            if(signum()==0) {
                return "0";
            }
            int tailingZeros = checkScaleNonZero((-(long)scale));
            StringBuilder buf;
            if(intCompact!=INFLATED) {
                buf = new StringBuilder(20+tailingZeros);
                buf.append(intCompact);
            } else {
                String str = intVal.toString();
                buf = new StringBuilder(str.length()+tailingZeros);
                buf.append(str);
            }
            for (int i = 0; i < tailingZeros; i++)
                buf.append('0');
            return buf.toString();
        }
        String str ;
        if(intCompact!=INFLATED) {
            str = Long.toString(Math.abs(intCompact));
        } else {
            str = intVal.abs().toString();
        }
        return getValueString(signum(), str, scale);
    }
 /**
     * Returns a {@code BigDecimal} which is numerically equal to
     * this one but with any trailing zeros removed from the
     * representation.  For example, stripping the trailing zeros from
     * the {@code BigDecimal} value {@code 600.0}, which has
     * [{@code BigInteger}, {@code scale}] components equals to
     * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
     * {@code scale}] components equals to [6, -2].  If
     * this BigDecimal is numerically equal to zero, then
     * {@code BigDecimal.ZERO} is returned.
     *
     * @return a numerically equal {@code BigDecimal} with any
     * trailing zeros removed.
     * @since 1.5
     */
    public BigDecimal stripTrailingZeros() {
        if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) {
            return BigDecimal.ZERO;
        } else if (intCompact != INFLATED) {
            return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);
        } else {
            return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);
        }
    }

demo

public class StringUtils {
    public static void main(String[] args) {
        System.out.println(BigDecimal.ZERO);
        System.out.println(new BigDecimal("2.0"));
        System.out.println(new Double("0"));
        System.out.println(new BigDecimal("2.00"));
        String d = new BigDecimal("100.10").stripTrailingZeros().toPlainString();
        System.out.println(d);
        System.out.println(new BigDecimal("100.10").stripTrailingZeros().toPlainString());
    }
}

结果:

在这里插入图片描述

方法二:

 private static final DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
    public static void main(String[] args) throws Exception{
        System.out.print( "格式化结果:");
        System.out.println(decimalFormat.format(new BigDecimal("10.10")));
    }

结果:

在这里插入图片描述

Java BigDecimal 小数点处理

保留两位小数

方法一:

{
   double   c=3.154215;
   java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
   String str = myformat.format(c);   
}

方式二:

{
   java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");
   df.format(你要格式化的数字);
   例:new java.text.DecimalFormat("#.00").format(3.1415926)
   #.00 表示两位小数 #.0000四位小数 以此类推...
}

方式三:

{
   double d = 3.1415926;
   String result = String .format("%.2f");
   %.2f %. 表示 小数点前任意位数   2 表示两位小数 格式后的结果为f 表示浮点型
}

四舍五入

{
double   f   =   111231.5585;
BigDecimal   b   =   new   BigDecimal(f);
//保留2位小数
double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
}
public class PreciseCompute {
//默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
 
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
 
public static double add(double v1, double v2) {
   BigDecimal b1 = new BigDecimal(Double.toString(v1));
   BigDecimal b2 = new BigDecimal(Double.toString(v2));
   return b1.add(b2).doubleValue();
}
 
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
 
public static double sub(double v1, double v2) {
   BigDecimal b1 = new BigDecimal(Double.toString(v1));
   BigDecimal b2 = new BigDecimal(Double.toString(v2));
   return b1.subtract(b2).doubleValue();
}
 
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2) {
   BigDecimal b1 = new BigDecimal(Double.toString(v1));
   BigDecimal b2 = new BigDecimal(Double.toString(v2));
   return b1.multiply(b2).doubleValue();
}
 
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
 
public static double div(double v1, double v2) {
   return div(v1, v2, DEF_DIV_SCALE);
}
 
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
   if (scale < 0) {
    throw 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).doubleValue();
}
 
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale) {
   if (scale < 0) {
    throw new IllegalArgumentException(
      "The scale must be a positive integer or zero");
   }
   BigDecimal b = new BigDecimal(Double.toString(v));
   BigDecimal ne = new BigDecimal("1");
   return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
 

my code:

private BigDecimal formatComma2BigDecimal(Object obj) {
		String val = String.valueOf(obj);
		if (val == null)
			return new BigDecimal("0.00");
 
		val = val.replaceAll(",", "");
		if (!isNumber(val))
			return new BigDecimal("0.00");
 
		BigDecimal decimal = new BigDecimal(val);
		decimal = decimal.setScale(2, RoundingMode.HALF_UP); 
		return decimal;
 
	}
	private String formatCommaAnd2Point(Object obj) {
		BigDecimal decimal = formatComma2BigDecimal(obj);
 
		DecimalFormat df = new DecimalFormat("#,###.00");
		String decimalStr = df.format(decimal).equals(".00")?"0.00":df.format(decimal);
		if(decimalStr.startsWith(".")){
			decimalStr = "0"+decimalStr;
		}
		return decimalStr;
	}
	private boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	private boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	private boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

详细还是参看JavaSE 帮助文档吧~以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java实现斗地主之洗牌发牌

    Java实现斗地主之洗牌发牌

    这篇文章主要为大家详细介绍了Java实现斗地主之洗牌发牌,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-06-06
  • Java并发之Semaphore工具类r的全面解析

    Java并发之Semaphore工具类r的全面解析

    Semaphore 是 java.util.concurrent中非常有用的并发编程工具类,它通常被用于限制对某个资源或资源池的并发访问数量,下面我们就来深入了解一下Semaphore的具体使用吧
    2024-02-02
  • mybatis中的异常BindingException详解

    mybatis中的异常BindingException详解

    这篇文章主要介绍了mybatis中的异常BindingException详解,此异常是mybatis中抛出的,意思是使用的这个方法找到,但是因为mapperScan()已经扫描到了Mapper类了,在绑定Mapper.xml时没有绑定到导致的,需要的朋友可以参考下
    2024-01-01
  • Java异常处理中同时有finally和return语句的执行问题

    Java异常处理中同时有finally和return语句的执行问题

    这篇文章主要介绍了Java异常处理中同时有finally和return语句的执行问题,首先确定的是一般finally语句都会被执行...然后,需要的朋友可以参考下
    2015-11-11
  • Java中PropertyDescriptor的用法及说明

    Java中PropertyDescriptor的用法及说明

    这篇文章主要介绍了Java中PropertyDescriptor的用法及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • 如何用SpringBoot 进行测试

    如何用SpringBoot 进行测试

    这篇文章主要介绍了如何用SpringBoot 进行测试,帮助大家更好的理解和使用springboot框架,感兴趣的朋友可以了解下
    2020-11-11
  • maven国内镜像配置的方法步骤

    maven国内镜像配置的方法步骤

    这篇文章主要介绍了maven国内镜像配置的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • 创建Spring Boot项目的几种方式总结(推荐)

    创建Spring Boot项目的几种方式总结(推荐)

    这篇文章主要介绍了创建Spring Boot项目的几种方式总结(推荐),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • 关于maven环境的安装及maven集成idea环境的问题

    关于maven环境的安装及maven集成idea环境的问题

    Maven 是一个基于 Java 的工具,所以要做的第一件事情就是安装 JDK。本文重点给大家介绍关于maven环境的安装及和idea环境的集成问题,感兴趣的朋友一起看看吧
    2021-09-09
  • 基于Java实现QQ登录注册功能的示例代码

    基于Java实现QQ登录注册功能的示例代码

    这篇文章主要和大家分享如何利用Java语言实现QQ登录、注册等功能。本文主要应用的技术有:GUI、JDBC、多线程等,需要的可以参考一下
    2022-05-05

最新评论