简体   繁体   中英

a method returning double adding to string and printing to 2 decimal places

I am trying to print a double returned from a method to 2 decimal places but I am having trouble as the method is called in the return of a string method.

I have tried using printf but I get an error. I am assuming this is because there is not only numbers.

heres the code.

public double monthlyPay()
{
    return annualSalary / 12;
}

public String toString()
{
    return super.toString() + " Monthly Pay = " + monthlyPay();
}

public void print()
{
    System.out.println(toString());
}

I am grateful for any help.

If you are trying to cut monthlyPay() to 2 decimal places you can go with:

double monthPay =  (double)Math.round(monthlyPay() * 100d) / 100d

return super.toString() + " Monthly Pay = " + monthPay);

Alternatively you can use a method like this to format your string:

import java.text.DecimalFormat;

public static String formatNumber(int decimals, double number) {
    StringBuilder sb = new StringBuilder(decimals + 2);
    sb.append("#.");
    for(int i = 0; i < decimals; i++) {
        sb.append("0");
    }
    return new DecimalFormat(sb.toString()).format(number);
}

It surely does output zeros aswell. Upon calling it with these parameters for example:

 String x =  formatNumber(3,5.1000); 

your output will be x = "5,100"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM