• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Round to n decimals?

 
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.
 
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
 
Sheriff
Posts: 21760
102
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!