• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

rounding a floating point number to specific precision

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Is there any function in Java that will help in round a floating point number to specific no of decimals?
Example: when rounding 3.1237 to 3 decimals the result shoud be 3.124 and 3.1233 should be 3.123.
Math.round() doesn't seem to do that.
All suggestions and pointers are highly appreciated.
Thanks,
-Hema

------------------
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, please read our user name policy. Your name is not a valid user name; please re-register with a first and last name. Thanks.
As for the question - well, to round to 3 digits for example, you could use <code>Math.round(1000 * arg) / 1000.0</code>. However if you print out the result, you may find that the results aren't quite like you want. E.g. you might see an answer like 3.12399999999996 instead of 3.124 - extremely close to what you wnat, but unattractive. Assuming you're really more interested in displaying numbers with a fixed number of digits (rather than rounding them off in the actual calcualtions), your best bet is to use the DecimalFormat class - see the tutorial here.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hema,
try this out.
--------
NumberFormat oNF = NumberFormat.getInstance(Locale.US);
oNF.setMinimumFractionDigits(0);
oNF.setMaximumFractionDigits(3);
String stFormatted = oNF.format(dbCurr);
--------
Satish
 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ooops.. It's been a while since I posted anything & I forgot to add my lastname. Sorry about it , I re-registered again.
Thanks Jim & Satish for yr valuable suggestions.
-Hema
 
Yeah, but does being a ninja come with a dental plan? And what about this tiny ad?
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic