Problems with Decimalformat

2019-08-26 03:40发布

问题:

Hey i am using the following code to format my numbers to have two decimal places

public String format(double num)
{
    String temp="";
    DecimalFormat df=new DecimalFormat("R.##");
    temp=temp+df.format(num);
    return temp;
}

When I print out the results it gives me the answeres with only one decimal place. Please can someone help me stop that.

回答1:

You use # in DecimalFormat which is the character that says "print the digit. if it is 0 leave it out."

You need to use 0 where 0 is also printed as 0.

E.g.

DecimalFormat df=new DecimalFormat("R.00");


回答2:

 BigDecimal bd = new BigDecimal(123.12331312);

System.out.print(bd.setScale(2,1));

try this



回答3:

Use following way to format

System.out.printf("%.2f",num);