Question

Possible Duplicate:
Is there an equivalent for toPrecision() in Java?

I created a method which suppose to limit the number to only 2 decimal places but what it does it shows numbers to 2 decimal places and then display zeros after that.

Also, from the number computation below I can notice that it rounds the numbers incorrectly. The numbers should be 478.03 129.06 348.97.

What's wrong here?

PS. I'm just following pseudocode and I can't import anything more than import java.io.*;

My output:

Employee's Last Name: dfsdfsdf
Employment Status (F or P): p
Hourly Pay Rate: 8.35
Hours Worked: 51.5
-------------------------------------------------------
Name    Status      Gross   Taxes   Net
dfsdfsdf    Part Time       478.040000  129.070000  348.970000

My code where I input all data, and then attempting to output it:

private static void outputData(String name, char status, double pay) 
{
    if (status == "p".charAt(0))
    {
        System.out.println("-------------------------------------------------------");
        System.out.println("Name\tStatus\t\tGross\tTaxes\tNet");
        System.out.printf("%s\tPart Time\t\t%f\t%f\t%f\n\n", 
                name, 
                roundDouble(pay), 
                roundDouble(calculateTaxes(pay)), 
                roundDouble(pay - calculateTaxes(pay)));
    }
    else if (status == "f".charAt(0))
    {
        System.out.println("-------------------------------------------------------");
    }
}

More code which is the method that should do conversion:

private static double roundDouble(double number) 
{
    return Double.parseDouble(String.format("%.2f", number));
}
Was it helpful?

Solution

try to do it like this:

private static double roundDouble(double number) 
{
    return java.lang.Math.round((number * 100) / 100.0));
}

OTHER TIPS

You could try NumberFormat instead

double value = 478.03123456789;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);

System.out.println(nf.format(value));

Outputs 478.03

ps - It might help with had the original values as well ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top