【问题标题】:DecimalFormat not working properly when input is xx.x当输入为 xx.x 时,DecimalFormat 无法正常工作
【发布时间】:2013-07-16 07:55:01
【问题描述】:

我有以下DecimalFormat 的代码。

import java.util.*;
import java.lang.*;
import java.text.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        double d = 50.12345;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.println(df.format(d));

        d = 50.0;
        df = new DecimalFormat("#.##");
        System.out.println(df.format(d));

        d = (double) (1*1.000/Integer.parseInt(2+"")/1.000*100);
        df = new DecimalFormat("#.##");
        System.out.print(df.format(d));

        }
}

这给了我如下输出。

50.12
50
50

我面临的问题是第二个数字。我想把它打印成 50.00。

知道我该怎么做吗?

Demo

【问题讨论】:

标签: java decimalformat


【解决方案1】:

使用 0.00 作为格式。 # 表示可选数字。

您可以在此处找到所有格式代码及其含义:http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

【讨论】:

    【解决方案2】:

    使用这个

        double d = 50.12345;
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println(df.format(d));
        d = 50.0;
        System.out.print(df.format(d));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      相关资源
      最近更新 更多