It's not a secret anymore!
The moose likes Java in General and the fly likes rounding off in java Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "rounding off in java" Watch "rounding off in java" New topic
Author

rounding off in java

Vasim Patel
Ranch Hand

Joined: Apr 29, 2004
Posts: 87
Hi

How do I round off the decimal in java to the nearest .05
e.g:
1.499 should 1.5.
But 1.49 should still be 1.49.
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
Check java.text.DecimalFormat


Mani
Quaerendo Invenietis
Vasim Patel
Ranch Hand

Joined: Apr 29, 2004
Posts: 87
Hi Mani

Thanks a lot. I am not too clear how to achieve what I want. DecimalFormat is more for formatting the decimal numbers.
I am interested in rounding off.
Can you please give an example using the API
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
There is a method called setMaximumFractionDigits() in that class.
That might be useful.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Vasim Patel:
How do I round off the decimal in java to the nearest .05
Since 0.05 is a decimal number, and float/double are binary approximations of decimal numbers, you can't be guaranteed to round exactly using them. If you just want to get close, try this:In words, you shift the rounding scale to be 1 instead of 0.05, round the value to nearest integer, and shift back. If you need exact decimal values, use java.math.BigDecimal.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: rounding off in java
 
Similar Threads
Problem with packages!!!
code doubt
problem with JTable printing (urgent)
diff b/w static final & final static
what is the latest version of java.how is it?