2

I saw Using BigDecimal to work with currencies but I have a little different problem.

I give object with BigDecimal parameters to PDF generation library and I can't use Formatter, only send objects. Is possible that default toString method always writes BigDecimal objects in format *.xx w.g 134.40 ?

I use setScale but it doesn't work for e.g. 134.300 because it writes 134.3 instead of 134.30

Community
  • 1
  • 1
plancys
  • 3,833
  • 2
  • 19
  • 26

2 Answers2

4

I assume the problem is that you have forgotten that BigDecimal is immutable and setScale doesn't alter the existing BigDecimal

BigDecimal decimal = BigDecimal.valueOf(134.4);
BigDecimal decimal2 = decimal.setScale(2, RoundingMode.HALF_UP);
System.out.println(decimal2);

prints

134.40

BTW to do the same thing with double

double d = 134.4;
System.out.printf("%.2f%n", d);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Just use NumberFormat.getCurrencyInstance().format(n) and pass the resulting string to the PDF generation library.

Nick Holt
  • 33,455
  • 4
  • 52
  • 58