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.
- When original num = 56565656.342 ==> I need 56,565,656.34
- When original num = 56565656 ==> I need 56,565,656.00
- 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.
DecimalFormat class would do it for you.... You will have to specify appropriate format.
Just use
NumberFormat
and specify the fraction digits, and rounding method, to print :Will print
** Edit **
Will produce the exact same result with the given code above.
Take a look at the DecimalFormat class.
Alternatively you can setScale method from the BigDecimal Class.
Yields:
EDIT: Also forgot to mention: If you are after precision, I would recommend you use the
setScale
method, using the.doubleValue()
method will yield adouble
which can cause loss of precision.