How to display a number with always 2 decimal points using BigDecimal?

喜你入骨 提交于 2019-11-28 09:39:57

BigDecimal is immutable, any operation on it including setScale(2, BigDecimal.ROUND_HALF_UP) produces a new BigDecimal. Correct code should be

        BigDecimal bd = new BigDecimal(1);
//      bd.setScale(2, BigDecimal.ROUND_HALF_UP);   bd.setScale does not change bd
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(bd);

output

1.00
corgrin

you can use the round up format

BigDecimal bd = new BigDecimal(2.22222);
System.out.println(bd.setScale(2,BigDecimal.ROUND_UP));

Hope this help you.

To format numbers in JAVA you can use:

 System.out.printf("%1$.2f", d);

where d is your variable or number

or

 DecimalFormat f = new DecimalFormat("##.00");  // this will helps you to always keeps in two decimal places
 System.out.println(f.format(d)); 

You need to use something like NumberFormat with appropriate locale to format

NumberFormat.getCurrencyInstance().format(bigDecimal);

BigDecimal.setScale would work.

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