• Post Reply Bookmark Topic Watch Topic
  • New Topic

BigDecimal not rounding properly in some cases?  RSS feed

 
Michael Remijan
Author
Ranch Hand
Posts: 131
7
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code to round a decimal to 2 decimal places and round half up.

BigDecimal bd = new BigDecimal(d);
return bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

During junit testing I was kind of amzed to find this failed for some numbers. For example, If I have 0.235 I'd expect the value to be 0.24 when it comes back however it doesn't "round half up" and remains 0.23.

Is this old news? Does anyone know why this is happening? What's the work-around?
 
Douglas Rohm
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens if you do 0.225 instead? I've seen rounding rules where you "round half up" depending on whether the preceding digit is even or odd. Perhaps Java is doing this?

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!