Java 保留几位小数

java 中常见的保留几位小数的操作,通常都会用到BigDecimal 类

例如:

  /**
     * 四舍五入
     */
    @Test
    public void test() {
        double num = 111231.5585;
        BigDecimal b = new BigDecimal(num);
        //保留2位小数
        double result = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.println(result);  //111231.56
    }

或者

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	      double f1 = 124.454654;
          java.text.DecimalFormat df = new java.text.DecimalFormat("#.000");
          f1 = Double.parseDouble(df.format(f1));
          System.out.println(f1);
	}

但是他们都有一个弊端,就是当数组较大时,会产生 科学计数法。

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	      double f1 = 1234324535;
          java.text.DecimalFormat df = new java.text.DecimalFormat("#.000");
          f1 = Double.parseDouble(df.format(f1));
          System.out.println(f1); //1.234324535E9
	}

如上所示。

然后查找如何消除科学计数法,找到博客  链接:https://blog.csdn.net/weixin_43992934/article/details/108006838

确实可以解决科学计数法的问题。

但是如果我希望得到的值,乘以100或者1000怎么办呢?于是想到移动小数点。

	/**
	 * 移动小数点
	 * @param str 待移动的字符串
	 * @param capacity 向右移动的位数
	 * @return
	 */
	public static String moveDot(String str,int capacity) {
		if (str.equals("0.000")) {
			return "0.0";
		}
		if (str.equals("0.0000")) {
			return "0.00";
		}
		int index = str.indexOf(".");
		char[] cas = str.toCharArray();
		
		for (int i = 0 ;i<capacity;i++) {
//			System.out.println(cas[index]);
			cas[index] = cas[index+1];
			cas[index+1] = '.';
			index = index+1;
		}
		System.out.println(new String(cas));
		return new String(cas);
	}

测试方法

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 BigDecimal b = new BigDecimal("1232432");
//		 保留三位小数
         String f = b.setScale(3, BigDecimal.ROUND_HALF_UP).toPlainString();
         moveDot(f,2); //123243200.0
	}

猜你喜欢

转载自blog.csdn.net/kanyun123/article/details/109996828