格式化为2到2位小数,前导0 [重复]

时间:2022-06-20 17:11:28

Possible Duplicate:
Round a double to 2 significant figures after decimal point

可能重复:将小数点后的两位有效数字舍入为2

I am trying to format a double to 2 decimal places with leading zeros and there's no luck. Here is my code:

我试图用前导零来格式化一个双精度到2位小数,并且没有运气。这是我的代码:

Double price = 32.0;
DecimalFormat decim = new DecimalFormat("#.##");
Double price2 = Double.parseDouble(decim.format(price));

And I want output to be 32.00 instead I get 32.0
Any solutions??

我希望输出为32.00而不是我得到32.0任何解决方案?

2 个解决方案

#1


49  

OP wants leading zeroes. If that's the case, then as per Tofubeer:

OP需要领先的零。如果是这样,那么根据Tofubeer:

    DecimalFormat decim = new DecimalFormat("0.00");

Edit:

Remember, we're talking about formatting numbers here, not the internal representation of the numbers.

请记住,我们在谈论格式化数字,而不是数字的内部表示。

    Double price = 32.0;
    DecimalFormat decim = new DecimalFormat("0.00");
    Double price2 = Double.parseDouble(decim.format(price));
    System.out.println(price2);

will print price2 using the default format. If you want to print the formatted representation, print using the format:

将使用默认格式打印price2。如果要打印格式化的表示,请使用以下格式打印:

    String s = decim.format(price);
    System.out.println("s is '"+s+"'");

In this light, I don't think your parseDouble() is doing what you want, nor can it.

从这个角度来看,我认为你的parseDouble()并不是你想要的,也不是。

#2


14  

Try this:

 DecimalFormat decim = new DecimalFormat("#.00");

#1


49  

OP wants leading zeroes. If that's the case, then as per Tofubeer:

OP需要领先的零。如果是这样,那么根据Tofubeer:

    DecimalFormat decim = new DecimalFormat("0.00");

Edit:

Remember, we're talking about formatting numbers here, not the internal representation of the numbers.

请记住,我们在谈论格式化数字,而不是数字的内部表示。

    Double price = 32.0;
    DecimalFormat decim = new DecimalFormat("0.00");
    Double price2 = Double.parseDouble(decim.format(price));
    System.out.println(price2);

will print price2 using the default format. If you want to print the formatted representation, print using the format:

将使用默认格式打印price2。如果要打印格式化的表示,请使用以下格式打印:

    String s = decim.format(price);
    System.out.println("s is '"+s+"'");

In this light, I don't think your parseDouble() is doing what you want, nor can it.

从这个角度来看,我认为你的parseDouble()并不是你想要的,也不是。

#2


14  

Try this:

 DecimalFormat decim = new DecimalFormat("#.00");