Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Round to n decimals?

 
Lee Carlson
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sridhar Santhanakrishnan
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look at the class java.lang.BigDecimal and the setScale() method
 
Rob Spoor
Sheriff
Pie
Posts: 20751
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An alternative is multiply by 100, then round, then divide by 100 again. BigDecimal is better (and more accurate) though.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic