innumonenu
asked on
BigDecimal formatting without any rounding
Hello All,
We have a requirement where we need to work with java.math.BigDecimal and format it in such a way so that the display would always have four decimal digits, appropriate commas and NO rounding up or down. Meaning,
Input Output
1 1.0000
0.5 0.5000
0.0004 0.0004
0.00085 0.0008
1000 1,000.0000
We tried to format the big decimal with DecimalFormat("#,##0.0000" ) but there is some rounding on the decimal value i.e., if input is 0.00006 then the output is 0.0001 whereas it shoud be just 0.0000.
Any help on this would be must useful. Thanks.
We have a requirement where we need to work with java.math.BigDecimal and format it in such a way so that the display would always have four decimal digits, appropriate commas and NO rounding up or down. Meaning,
Input Output
1 1.0000
0.5 0.5000
0.0004 0.0004
0.00085 0.0008
1000 1,000.0000
We tried to format the big decimal with DecimalFormat("#,##0.0000"
Any help on this would be must useful. Thanks.
Do you need 4 decimal places always unless it has more? Or do you want the decimals to reflect the number like:
1
.5
23.455
2.0000005
1
.5
23.455
2.0000005
ASKER
Like I said, we always require 4 decimal digits if the input has it or not. For example,
Input Output
1 1.0000
0.5 0.5000
0.0004 0.0004
0.00085 0.0008
1000 1,000.0000
Input Output
1 1.0000
0.5 0.5000
0.0004 0.0004
0.00085 0.0008
1000 1,000.0000
ASKER
DecimalFormat("#,##0.0000" ) almost satisfies the requirement but there is some rounding on the decimal value i.e., if input is 0.00006 then the output is 0.0001 whereas it shoud be just 0.0000.
BigDecimal ba = new BigDecimal(1000);
BigDecimal bb = new BigDecimal(0.5);
BigDecimal bc = new BigDecimal(0.00006);
DecimalFormat myFormat = new DecimalFormat("#,##0.0000" );
ba = ba.setScale(4,BigDecimal.R OUND_DOWN) ;
bb = bb.setScale(4,BigDecimal.R OUND_DOWN) ;
bc = bc.setScale(4,BigDecimal.R OUND_DOWN) ;
System.out.println(myForma t.format(b a));
System.out.println(myForma t.format(b b));
System.out.println(myForma t.format(b c));
1.000,0000
0,5000
0,0000
BigDecimal bb = new BigDecimal(0.5);
BigDecimal bc = new BigDecimal(0.00006);
DecimalFormat myFormat = new DecimalFormat("#,##0.0000"
ba = ba.setScale(4,BigDecimal.R
bb = bb.setScale(4,BigDecimal.R
bc = bc.setScale(4,BigDecimal.R
System.out.println(myForma
System.out.println(myForma
System.out.println(myForma
1.000,0000
0,5000
0,0000
(I have 1.000,0000 and not 1,000.0000 according to my Locale (fr-BE))
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks matthew016. Not sure whether you above solution will work for input like 1.9? Will the output be 1.9000?
http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_DOWN