File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Round to n decimals? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Round to n decimals?" Watch "Round to n decimals?" New topic

Round to n decimals?

Lee Carlson

Joined: Nov 29, 2009
Posts: 1
How does one round(123.456) to 123.46?

Everything I've found so far says round() returns a whole number, so round(123.45) returns 123. The languages I'm most fluent in have a round(value, number of decimals) function to handle this.

I expect I either haven't run across it yet or haven't looked in the right place.

FYI, I've been programming for close to 25+ years (Progress, 4GL/ABL) but new to Java. I'm hoping to complete my SCJP in the not too distant future.


Lee Carlson
Carlson Consulting, Inc.
Owatonna, Minnesota
Sridhar Santhanakrishnan
Ranch Hand

Joined: Mar 20, 2007
Posts: 317
look at the class java.lang.BigDecimal and the setScale() method
Rob Spoor

Joined: Oct 27, 2005
Posts: 19720

An alternative is multiply by 100, then round, then divide by 100 again. BigDecimal is better (and more accurate) though.

How To Ask Questions How To Answer Questions
subject: Round to n decimals?