代码之家  ›  专栏  ›  技术社区  ›  Bat_Programmer

以0开头的小数点后两位数格式[重复]

  •  33
  • Bat_Programmer  · 技术社区  · 14 年前

    可能重复:
    Round a double to 2 significant figures after decimal point

    我正在尝试用前导零将小数点后两位数格式化,但没有运气。 这是我的代码:

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

    我希望输出 32.00 取而代之的是我得到 32.0
    有什么解决办法吗??

    2 回复  |  直到 12 年前
        1
  •  51
  •   Hardik Mishra    12 年前

    OP需要前导零。如果是这样,那么根据Tofuber:

        DecimalFormat decim = new DecimalFormat("0.00");
    

    编辑:

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

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

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

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

    从这个角度看,我不认为你 parseDouble() 做你想做的,也做不到。

        2
  •  14
  •   TofuBeer    14 年前

    试试这个:

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