Formatting a number with correct decimal scale

2019-08-12 04:18发布

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.

3条回答
时光不老,我们不散
2楼-- · 2019-08-12 04:54

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

查看更多
做自己的国王
3楼-- · 2019-08-12 04:55

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.

查看更多
Anthone
4楼-- · 2019-08-12 04:57

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.

查看更多
登录 后发表回答