We help IT Professionals succeed at work.

how to round?

Mark
Mark used Ask the Experts™
on
I give up - I'm trying to round a number to 2 decimal places. I've tried various permutations of

federalTaxableEarnings.setScale(0,RoundingMode.ROUND_HALF_UP);

but I get errors. Examples on the web haven't helped me.

What is the correct syntax and what imports do I need?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Why don't try something easier just like:

float rounded = ((int)(your_number*100+0.5))/100;

hope it helps.
Awarded 2011
Awarded 2011

Commented:
Just use DecimalFormat and pattern, like in this example:

http://www.roseindia.net/java/beginners/DecimalFormatExample.shtml
Awarded 2011
Awarded 2011

Commented:
But use pattern with two decimal digits:


import java.text.DecimalFormat;
import java.text.NumberFormat;
 
public class DecimalFormatExample
{
  public static void main(String args[])
  {
  double amount = 2192.015;
  NumberFormat formatter = new DecimalFormat("#0.00");
  System.out.println("The Decimal Value is:"+formatter.format(amount));
  }
}  
Awarded 2011
Awarded 2011

Commented:
If you need to round only positive numbers then
(int) (f+0.5)

will also be working, but if you happen to have nefgative number that ay give wriong result
Awarded 2011
Awarded 2011

Commented:
This is how it worked for me:

import java.text.DecimalFormat;
import java.text.NumberFormat;

        double amount = 2192.0154;
  NumberFormat formatter = new DecimalFormat("#0.00");
  System.out.println("The Decimal Value is:"+formatter.format(amount));

Open in new window



The Decimal Value is:2192.02

Open in new window

Author

Commented:
Thanks - but not quite what I want. This is not just for displaying. I want to use the rounded value for calculating, so I want the values rounded first, then I'll do the math.

And I'm not rounding to a whole number, so adding 0.5 and converting to int isn't what I want.

I suppose I could do myNumber.add(new BigDecimal("0.005"), but I understand that the setScale will actually keep it to the specified positions ... if I can figure it out.

Also, the add 0.005 thing isn't quite precise either because it will create e.g.

2.5651 + 0.005 = 2.5701 which is not 2.57.

Please try what I said: I have added 0.5 after multiply the number by 100, and then I divide by 100, so this formula is rounding to two decimals (like adding 0.005). Please try this:

float rounded = ((int)(your_number*100+0.5))/100;
Awarded 2011
Awarded 2011

Commented:
After you format you can take

doube d = Double.parseDouble((formatter.format(amount)));

and then you'll operate with the value
Top Expert 2016

Commented:
>> I want to use the rounded value for calculating

Why is that? It will just make the calculation less precise

Commented:
That's not necessarily true.  I have written engineering software, and often we are forced (by the engineering specifications) to round in the intermediate calculations and use the rounded numbers for the rest of the calculations.  Not only is the extra precision meaningless, but it makes the math 'look' wrong, because the results can not be verified by hand looking at the intermediate numbers in the report if you carry the extra digits forward.
Top Expert 2016

Commented:
>>federalTaxableEarnings.setScale(0,RoundingMode.ROUND_HALF_UP);

Don't forget to reassign btw as BigX classes are immutable
federalTaxableEarnings = federalTaxableEarnings.setScale(0,RoundingMode.ROUND_HALF_UP);

Open in new window

Awarded 2011
Awarded 2011
Commented:
This is how it works (should be setScale(2, RoundingMode.HALF_UP);)

This is the test (see output):
      BigDecimal federalTaxableEarnings =  new BigDecimal(40.0276);
 federalTaxableEarnings = federalTaxableEarnings.setScale(2, RoundingMode.HALF_UP);
        System.out.println("earning: " + federalTaxableEarnings);
        

Open in new window

Output:
earning: 40.03

Open in new window

Why not my proposal ? I think it's the easyest way and has some mathematical beauty:

float rounded = ((int)(your_number*100+0.5))/100;

Author

Commented:
for_yan: that looks like a winner! I had the wrong mode constant(ROUND_HALF_UP versus HALF_UP). The example I was looking at was wrong. Also, it wasn't obvious that the '2' meant 2 decimal positions, though I thought it might -- I couldn't test that without the right mode constant. Thanks.

CEHJ:
>> I want to use the rounded value for calculating
>Why is that? It will just make the calculation less precise

schubach is right. It's about making the math "look" right. As you might guess, this calculation is for Federal tax. The check recipient will see the rounded taxable number on his/her check and the calculated tax could be visually off a penny-ish using the unrounded number, even if it is technically more "accurate".

gplana: > Why not my proposal ?

These are BigDecimals, not floats, so getting that to an int and back isn't quite as elegant as your code and, in fact, looks quite horrendous:

BigDecimal newValue = new BigDecimal(((myNumber.multiply(new BigDecimal("100")).add(new BigDecimal("0.5")).intValue());

 I think you would agree that for_yan's: federalTaxableEarnings.setScale(2, RoundingMode.HALF_UP); is much simpler and more elegant.