• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

rounding off in java

 
Vasim Patel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check java.text.DecimalFormat
 
Vasim Patel
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a method called setMaximumFractionDigits() in that class.
That might be useful.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic