最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用BigDecimal去掉小數(shù)點后無用的0

 更新時間:2021年08月14日 10:40:52   作者:采坑先鋒  
這篇文章主要介紹了使用BigDecimal去掉小數(shù)點后無用的0操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

如題:BigDecimal去掉小數(shù)點后無用的0

比如:數(shù)據(jù)庫存儲的是Decimal(5,2)類型保留兩位數(shù)。

如果展示數(shù)據(jù)5.00,5.10等字樣感覺很不爽,如何做呢?

只戰(zhàn)術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 小數(shù)點處理

保留兩位小數(shù)

方法一:

{
   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(你要格式化的數(shù)字);
   例:new java.text.DecimalFormat("#.00").format(3.1415926)
   #.00 表示兩位小數(shù) #.0000四位小數(shù) 以此類推...
}

方式三:

{
   double d = 3.1415926;
   String result = String .format("%.2f");
   %.2f %. 表示 小數(shù)點前任意位數(shù)   2 表示兩位小數(shù) 格式后的結果為f 表示浮點型
}

四舍五入

{
double   f   =   111231.5585;
BigDecimal   b   =   new   BigDecimal(f);
//保留2位小數(shù)
double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
}
public class PreciseCompute {
//默認除法運算精度
private static final int DEF_DIV_SCALE = 10;
 
/**
* 提供精確的加法運算。
* @param v1 被加數(shù)
* @param v2 加數(shù)
* @return 兩個參數(shù)的和
*/
 
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 被減數(shù)
* @param v2 減數(shù)
* @return 兩個參數(shù)的差
*/
 
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 被乘數(shù)
* @param v2 乘數(shù)
* @return 兩個參數(shù)的積
*/
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();
}
 
/**
* 提供(相對)精確的除法運算,當發(fā)生除不盡的情況時,精確到
* 小數(shù)點以后10位,以后的數(shù)字四舍五入。
* @param v1 被除數(shù)
* @param v2 除數(shù)
* @return 兩個參數(shù)的商
*/
 
public static double div(double v1, double v2) {
   return div(v1, v2, DEF_DIV_SCALE);
}
 
/**
* 提供(相對)精確的除法運算。當發(fā)生除不盡的情況時,由scale參數(shù)指
* 定精度,以后的數(shù)字四舍五入。
* @param v1 被除數(shù)
* @param v2 除數(shù)
* @param scale 表示表示需要精確到小數(shù)點以后幾位。
* @return 兩個參數(shù)的商
*/
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();
}
 
/**
* 提供精確的小數(shù)位四舍五入處理。
* @param v 需要四舍五入的數(shù)字
* @param scale 小數(shù)點后保留幾位
* @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 幫助文檔吧~以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • 詳解Java中的流程控制

    詳解Java中的流程控制

    今天帶大家復習Java基礎知識,文中對Java流程控制作了非常詳細的介紹及代碼示例,對正在學習Java的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05
  • Java線程之間的共享與協(xié)作詳解

    Java線程之間的共享與協(xié)作詳解

    這篇文章主要介紹了Java線程之間的共享與協(xié)作詳解,進程是操作系統(tǒng)進行資源分配的最小單位,線程是進程的一個實體,是CPU調度和分派的基本單位,它是比經(jīng)常更小的、能夠獨立運行的基本單位
    2022-07-07
  • springBoot項目常用目錄解讀

    springBoot項目常用目錄解讀

    這篇文章主要介紹了springBoot項目常用目錄解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Java中的自旋鎖與適應性自旋鎖詳解

    Java中的自旋鎖與適應性自旋鎖詳解

    這篇文章主要介紹了Java中的自旋鎖與適應性自旋鎖詳解,在多處理器環(huán)境中某些資源的有限性,有時需要互斥訪問,這時候就需要引入鎖的概念,只有獲取了鎖的線程才能對資源進行訪問,多線程的核心是CPU的時間分片,所以同一時刻只能有一個線程獲取到鎖,需要的朋友可以參考下
    2023-10-10
  • IDEA如何修改maven的JVM啟動內存參數(shù)

    IDEA如何修改maven的JVM啟動內存參數(shù)

    這篇文章主要介紹了IDEA如何修改maven的JVM啟動內存參數(shù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-09-09
  • 帶你了解Java數(shù)據(jù)結構和算法之2-3-4樹

    帶你了解Java數(shù)據(jù)結構和算法之2-3-4樹

    這篇文章主要為大家介紹了Java數(shù)據(jù)結構和算法之2-3-4樹,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01
  • java springmvc亂碼解決歸納整理詳解

    java springmvc亂碼解決歸納整理詳解

    本篇文章介紹了java 中spring mvc 解決亂碼的問題方法實例,需要的朋友可以參考下
    2017-04-04
  • 淺談Java并發(fā)編程之Lock鎖和條件變量

    淺談Java并發(fā)編程之Lock鎖和條件變量

    這篇文章主要介紹了淺談Java并發(fā)編程之Lock鎖和條件變量,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-08-08
  • spring cloud oauth2 feign 遇到的坑及解決

    spring cloud oauth2 feign 遇到的坑及解決

    這篇文章主要介紹了spring cloud oauth2 feign 遇到的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • SpringBoot調用對方webService接口的幾種方法示例

    SpringBoot調用對方webService接口的幾種方法示例

    平常我們開發(fā)調用接口一般會用到幾種數(shù)據(jù)格式,比如有restful的,這個是目前最流行的,也是最簡單開發(fā)的,還有一種就是webservice數(shù)據(jù)格式,本文給大家介紹了幾種SpringBoot調用對方webService接口的方法,文中有相關的代碼示例供大家參考,需要的朋友可以參考下
    2023-11-11

最新評論

会理县| 菏泽市| 安庆市| 铁力市| 五峰| 肃北| 宜宾县| 江达县| 宿迁市| 吉林市| 泸定县| 永川市| 竹溪县| 肥乡县| 稷山县| 阳西县| 沈丘县| 东宁县| 普宁市| 宜兴市| 广州市| 达尔| 宜兴市| 鄄城县| 霍林郭勒市| 万宁市| 华蓥市| 定兴县| 陇南市| 会理县| 渝中区| 故城县| 保靖县| 开原市| 潍坊市| 栾川县| 红河县| 海林市| 蓝山县| 柘城县| 宣化县|