Problems with Decimalformat

2019-08-26 02:52发布

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.

3条回答
仙女界的扛把子
2楼-- · 2019-08-26 03:34

Use following way to format

System.out.printf("%.2f",num);
查看更多
别忘想泡老子
3楼-- · 2019-08-26 03:37

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");
查看更多
女痞
4楼-- · 2019-08-26 03:38
 BigDecimal bd = new BigDecimal(123.12331312);

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

try this

查看更多
登录 后发表回答