Formatting a number with correct decimal scale

余生长醉 提交于 2019-12-11 09:32:46

问题


I need to format a number with scale of 2 decimal places. The original number may be a whole number or a number with three decimal places. However the result should be formatted to have commas and also two decimal places always regardless of whether the original number is whole number or having decimal places.

  1. When original num = 56565656.342 ==> I need 56,565,656.34
  2. When original num = 56565656 ==> I need 56,565,656.00
  3. When original num = 56565656.7 ==> I need 56,565,656.70

I am using the following code which is formatting the code but its failing to add the two decimal places in the above 2 & 3 cases.

String originalNumber = "56565656.7";
BigDecimal b = new BigDecimal(originalNumber).setScale(2, BigDecimal.ROUND_HALF_UP);
String formattedNumber = NumberFormat.getInstance().format(b);

Please let me know if there is any way to accomplish this in efficeint way.

Thanks in advance.


回答1:


Take a look at the DecimalFormat class.

Alternatively you can setScale method from the BigDecimal Class.

        BigDecimal bg1 = new BigDecimal("56565656.342");
        BigDecimal bg2 = new BigDecimal("56565656.00");
        BigDecimal bg3 = new BigDecimal("56565656.70");

        DecimalFormat df = new DecimalFormat("###,###.00");
        System.out.println(df.format(bg1.doubleValue()));
        System.out.println(df.format(bg2.doubleValue()));
        System.out.println(df.format(bg3.doubleValue()));

        System.out.println(bg1.setScale(2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bg2.setScale(2, BigDecimal.ROUND_HALF_UP));
        System.out.println(bg3.setScale(2, BigDecimal.ROUND_HALF_UP));

Yields:

56,565,656.34
56,565,656.00
56,565,656.70
56565656.34
56565656.00
56565656.70

EDIT: Also forgot to mention: If you are after precision, I would recommend you use the setScale method, using the .doubleValue() method will yield a double which can cause loss of precision.




回答2:


Just use NumberFormat and specify the fraction digits, and rounding method, to print :

String [] originalNumbers = new String[] {
   "56565656.342",
   "56565656.7",
   "56565656"
};

NumberFormat df = NumberFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.HALF_UP);

for (String number : originalNumbers) {
   String formattedNumber = df.format(new BigDecimal(number));

   System.out.println(formattedNumber);
}

Will print

56,565,656.34
56,565,656.70
56,565,656.00

** Edit **

DecimalFormat df = new DecimalFormat("#,###.00");

Will produce the exact same result with the given code above.




回答3:


DecimalFormat class would do it for you.... You will have to specify appropriate format.



来源:https://stackoverflow.com/questions/11858485/formatting-a-number-with-correct-decimal-scale

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