wood burning stoves 2.0*
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 OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Round to n decimals?" Watch "Round to n decimals?" New topic
Author

Round to n decimals?

Lee Carlson
Greenhorn

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.

TIA.


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
Sheriff

Joined: Oct 27, 2005
Posts: 19725
    
  20

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Round to n decimals?