1

I am using BigDecimal as follows:

BigDecimal val = object.getValue();//it returns BigDecimal type value

val contains 12.2300. I want to display 12.23 on my page. How can I do this?

Pops
  • 29,209
  • 36
  • 130
  • 150
Naresh
  • 235
  • 1
  • 7
  • 18

2 Answers2

4

Use DecimalFormat:

String formatted = new DecimalFormat("#.##").format(val);
Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
1

you can use DecimalFormat or you can manipulate it with String operations

        public static String format(BigDecimal big, int precision){
            String bigS = big.toString();
            int index = bigS.indexOf('.');
            String add = bigS.substring(index, index + precision + 1);
            String formatted = big.longValue() + "" + add;

            return formatted;
        }

        public static void main(String[] args) {

            BigDecimal big = new BigDecimal(2342342232.23232);
            System.out.println(format(big, 2));
            System.out.println(format(big, 3));
        }

Of course, DecimalFormat is clever way