Java BigDecimal remove decimal and trailing numbers

岁酱吖の 提交于 2019-11-28 09:03:53

Try number.toBigInteger().toString()

Use this.

BigDecimal truncated= number.setScale(0,BigDecimal.ROUND_DOWN);

BigDecimal without fractions is BigInteger. Why don't you just use BigInteger?

Here's the most elegant way I found to resolve this:

public static String convertDecimalToString (BigDecimal num){
    String ret = null;
    try {
        ret = num.toBigIntegerExact().toString();
    } catch (ArithmeticException e){
        num = num.setScale(2,BigDecimal.ROUND_UP); 
        ret = num.toPlainString();
    }
    return ret;
}
Vinayak Patil
private void showDoubleNo(double n) {
    double num = n; 
    int decimalPlace = 2; 
    BigDecimal bd = new BigDecimal(num); 
    bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP); 
    System.out.println("Point is "+bd); 
}
public static String convertBigDecimalToString(BigDecimal bg) {
      System.out.println("Big Decimal Value before its convertion :" + bg.setScale(2, BigDecimal.ROUND_HALF_UP));

      String bigDecStringValue = bg.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();

      System.out.println("Big Decimal String Value after removing Decimal places is :" + bigDecStringValue);

      return bigDecStringValue;
}

Please note : I have used 'BigDecimal.ROUND_HALF_UP' , just to make sure, Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!