Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

round()  RSS feed

 
Jesse Walker
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know round() will round to the nearest whole number but is there anything that will just round to 2 decimal places, the hundredth?
 
John Bartlett
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If you use a BigDecimal you can use the setScale(int newScale, int roundingMode) method.

John
 
Jim Hardin
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, as John said, BigDecimal method setScale(int newScale, int roundingMode) is, I was also thinking, the closest thing to an out of the box scaling and rounding solution which will allow you to round to two decimal places (hundredths). As for rounding mode, however, I ran into confusion with the way I expected ROUND_HALF_UP to work -- BigDecimal, setScale() and ROUND_HALF_UP... . I do not think you will find a roundingMode which matches the way Math.round() works unless I overlooked something (I found this quite surprising).
[ April 04, 2007: Message edited by: Jim Harding ]
 
Paul Clapham
Sheriff
Posts: 22502
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The usual quick and dirty way to do this is:

1. Multiply by 100.
2. Round to the nearest integer.
3. Divide by 100.
 
Jim Hardin
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Resulting in an inexact unscaled approximation, and only useful with small(ish) numbers.
-Jim
[ April 04, 2007: Message edited by: Jim Hardin ]
 
Jesse Walker
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is their a way to convert a double to a BigDecimal?
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jesse Walker:
is their a way to convert a double to a BigDecimal?


Um, have you read the javadocs of BigDecimal and its constructors?
 
Joshua Smith
Ranch Hand
Posts: 193
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

BigDecimal(double val)
Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value.


http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!