Java BigDecimal remove decimal and trailing numbers

前端 未结 6 1944
野的像风
野的像风 2020-12-09 16:46

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

6条回答
  •  臣服心动
    2020-12-09 17:29

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

提交回复
热议问题