0

I have a property called m_FOBST which contains the following number: 1.5776. Here I'm trying to round it:

   this.m_FOBST.setScale(2, BigDecimal.ROUND_HALF_EVEN)

However, I get the number 1.60 when I should be getting 1.58.

Can anyone explain why?

Leigh
  • 28,765
  • 10
  • 55
  • 103
  • 1
    I can't duplicate this, i get: groovy:000> d = new BigDecimal("1.5776") ===> 1.5776 groovy:000> d1 = d.setScale(2, BigDecimal.ROUND_HALF_EVEN) ===> 1.58 – Nathan Hughes May 09 '13 at 14:57
  • Try setting scale to 3? – wchargin May 09 '13 at 14:58
  • See http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html?m=1 – wchargin May 09 '13 at 14:59
  • 1
    `System.out.println(new BigDecimal("1.5776").setScale(2, BigDecimal.ROUND_HALF_EVEN));` prints `1.58` too. – Keppil May 09 '13 at 15:01
  • As another note, you should use `setScale(2, RoundingMode.HALF_EVEN)`, the version you use here is considered a legacy method. – Keppil May 09 '13 at 15:05

1 Answers1

4

BigDecimal is immutable - make sure you are using the value returned by the setScale() method.

BigDecimal bd = new BigDecimal("1.5776");

bd = bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);

In this case, bd is 1.58

manub
  • 3,990
  • 2
  • 24
  • 33
  • 2
    He probably is, since he said the answer was 1.60 (and BigDecimal doesn't round anything by default) – Marlon Bernardes May 09 '13 at 14:59
  • 4
    You should always use the `String` constructor when creating `BigDecimal` from a floating point number. – Keppil May 09 '13 at 15:00
  • @Keppil Why do you say that? – sdoca May 09 '13 at 15:01
  • thanks @Keppil - you're right. You do that because `double` and `float` are not exact representation of floating point numbers, this is the first reason why you want to use `BigDecimal` – manub May 09 '13 at 15:02
  • 2
    @sdoca: Floating point numbers are not exact. Run the following line to see what I mean: `System.out.println(new BigDecimal(1.5776));` – Keppil May 09 '13 at 15:02
  • @sdoca Quoting the javadocs: "[...]Note: the results of this constructor can be somewhat unpredictable [...]" http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigDecimal.html#BigDecimal(double) – Marlon Bernardes May 09 '13 at 15:03
  • @Keppil, interesting! Thanks! – sdoca May 09 '13 at 15:05
  • I copied the exactly same code that you put @manub, and get the correct answer, but i can´t get this using my property. So I did this `BigDecimal bd2 = this.m_FOBST; bd2 = bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);' And it worked, thank you so much. – Talita Albuquerque May 09 '13 at 15:09