Java BigDecimal remove decimal and trailing numbers

元气小坏坏 提交于 2019-11-27 02:37:08

问题


I'm new to Java and trying to take a BigDecimal (for example 99999999.99) and convert it to a string but without the decimal place and trailing numbers. Also, I don't want commas in the number and rounding is not needed.

I've tried:

Math.Truncate(number)

but BigDecimal is not supported.

Any ideas?

Thanks very much.


回答1:


Try number.toBigInteger().toString()




回答2:


Use this.

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



回答3:


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




回答4:


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;
}



回答5:


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); 
}



回答6:


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



来源:https://stackoverflow.com/questions/1316945/java-bigdecimal-remove-decimal-and-trailing-numbers

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