Java BigDecimal remove decimal and trailing numbers

前端 未结 6 1924
野的像风
野的像风 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:08

    Use this.

    BigDecimal truncated= number.setScale(0,BigDecimal.ROUND_DOWN);
    
    0 讨论(0)
  • 2020-12-09 17:10

    Try number.toBigInteger().toString()

    0 讨论(0)
  • 2020-12-09 17:18

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

    0 讨论(0)
  • 2020-12-09 17:23
    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); 
    }
    
    0 讨论(0)
  • 2020-12-09 17:24
    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

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题