Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# round()

Jesse Walker
Ranch Hand
Posts: 50
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
Hi,

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

John

Jim Hardin
Ranch Hand
Posts: 46
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
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
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
is their a way to convert a double to a BigDecimal?

Ulf Dittmer
Rancher
Posts: 42972
73
Originally posted by Jesse Walker:
is their a way to convert a double to a BigDecimal?

Joshua Smith
Ranch Hand
Posts: 193

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.