Naresh
Naresh

Reputation: 243

How can I specify the number of decimal places of a BigDecimal to print?

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?

Upvotes: 1

Views: 1627

Answers (2)

user467871
user467871

Reputation:

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

Upvotes: 1

Bozho
Bozho

Reputation: 597124

Use DecimalFormat:

String formatted = new DecimalFormat("#.##").format(val);

Upvotes: 4

Related Questions