• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Rounding off numbers?

 
m brown
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay, i know this is easy, but ive been up all night and my brain just froze.
its for the following problem


" The rounding rules for
tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax."

basically i just need to round the tax off to the nearest 0.5

i looked in my books and searched google they were no help.


so lets say i have

double tax;

and the tax value is 1.499.

how do i round that off to point 1.5?
 
Mark Van Tuyl
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To display the rounded value, you can use something like this:
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Careful... DecimalFormat uses a ROUND_HALF_EVEN mode, which rounds "towards the 'nearest neighbor' unless both neighbors are equidistant, in which case, round towards the even neighbor."

This is probably not what you expect. For example, 0.15 would round to 0.2, but 0.25 would also round to 0.2 (because 2 is even). Similarly, 0.35 and 0.45 would both round to 0.4.



Run the code below to verify.

I suggest using instances of BigDecimal rather than doubles. This provides the precision lacking from floating-point primitives, and also offers 8 different rounding modes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic