【问题标题】:In java I need help formatting with ("%.2f", int); it keeps outputting ##.##.#在java中我需要帮助格式化 ("%.2f", int);它一直在输出##.##.#
【发布时间】:2014-03-27 15:35:03
【问题描述】:

我正在尝试打印只有两位小数的双精度,但以下代码将其显示为 ##.##.#

 double x, i = 3, j = 3, y;


        x = Math.pow(i, j);
        System.out.printf("two decimal places is: %.2f", x);

【问题讨论】:

  • 您确定您正在运行该代码吗?
  • 这是我的输出:两位小数是:27.00
  • 是的,这是我目前唯一要做的事情。
  • 您能否发布您的 IDE 或运行此代码的任何位置的确切输出?
  • 如何指定语言环境:System.out.printf(Locale.US, "two decimal places is: %.2f", x);

标签: java number-formatting


【解决方案1】:

您应该尝试DecimalFormat。使用指定前导零和尾随零的0.00 模式,因为使用的是 0 字符而不是井号 (#)。

x = Math.pow(i, j);
//System.out.format("two decimal places is: %.2f", x);

DecimalFormat decimalFormat = new DecimalFormat("0.00");
System.out.println("two decimal places is: " + decimalFormat.format(x));

但正如 cmets 部分所述,请尝试向我们发布确切的控制台输出,它可以帮助我们找出您的代码无法正常工作的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多