Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Round to n decimals?  RSS feed

 
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: 21256
87
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.
 
No one can make you feel inferior without your consent - Eleanor Roosevelt. tiny ad:
Thread Boost - a very different sort of advertising
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!