Problems with Decimalformat

随声附和 提交于 2019-12-25 11:35:24

问题


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);


来源:https://stackoverflow.com/questions/17236335/problems-with-decimalformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!