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

回眸只為那壹抹淺笑 提交于 2019-11-27 03:04:25

问题


I am using BigDecimal to get some price values. Requirement is something like this, what ever the value we fetch from database, the displayed valued should have 2 decimal points.

Eg:

fetched value is 1 - should be displayed as 1.00
fetched value is 1.7823 - should be displayed as 1.78

I am using setScale(2, BigDecimal.ROUND_HALF_UP) but still some places, if the data from DB is a whole number then the same is being displayed !!

I mean if the value is 0 from DB its displayed as 0 only. I want that to be displayed as 0.00

Thanks


回答1:


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



回答2:


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.




回答3:


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



回答4:


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

NumberFormat.getCurrencyInstance().format(bigDecimal);



回答5:


BigDecimal.setScale would work.



来源:https://stackoverflow.com/questions/14515640/how-to-display-a-number-with-always-2-decimal-points-using-bigdecimal

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