This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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: 20077

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
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Round to n decimals?
It's not a secret anymore!