如何在Java中打印保留2位小数的浮点数?

发布于 2024-08-27 03:54:28 字数 35 浏览 11 评论 0原文

我可以使用 System.out.print 来实现吗?

Can I do it with System.out.print?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

笑梦风尘 2024-09-03 03:54:28

您可以使用 printf 方法,如下所示:

System.out.printf("%.2f", val);

简而言之,%.2f 语法告诉 Java 返回您的具有 2 位小数 (.2) 的变量 (val),以浮点数 (f) 的十进制表示形式从开头开始格式说明符 (%)。

除了 f 之外,您还可以使用其他转换字符:

  • d:十进制整数
  • o:八进制整数
  • e:浮动- 科学记数法中的点

You can use the printf method, like so:

System.out.printf("%.2f", val);

In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

There are other conversion characters you can use besides f:

  • d: decimal integer
  • o: octal integer
  • e: floating-point in scientific notation
幽梦紫曦~ 2024-09-03 03:54:28

您可以使用 DecimalFormat。使用它的一种方法:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

另一种方法是使用 #.## 格式构造它。

我发现所有格式化选项的可读性都不如调用格式化方法,但这是一个偏好问题。

You can use DecimalFormat. One way to use it:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

Another one is to construct it using the #.## format.

I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.

坏尐絯 2024-09-03 03:54:28

我建议使用 String.format() 如果您需要在代码中将值作为String

例如,您可以按以下方式使用String.format()

float myFloat = 2.001f;

String formattedString = String.format("%.02f", myFloat);

I would suggest using String.format() if you need the value as a String in your code.

For example, you can use String.format() in the following way:

float myFloat = 2.001f;

String formattedString = String.format("%.02f", myFloat);
浮云落日 2024-09-03 03:54:28
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
猥︴琐丶欲为 2024-09-03 03:54:28
float f = 102.236569f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
float f = 102.236569f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
朦胧时间 2024-09-03 03:54:28

您可以使用下面的快速代码,该代码最后会自行更改。在点后添加多少个 as 所指的零

float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");  
y1 = Float.valueOf(df.format(y1));

变量 y1 之前等于 0.123456789。代码之后,它仅变为 0.12

You may use this quick codes below that changed itself at the end. Add how many zeros as refers to after the point

float y1 = 0.123456789;
DecimalFormat df = new DecimalFormat("#.00");  
y1 = Float.valueOf(df.format(y1));

The variable y1 was equals to 0.123456789 before. After the code it turns into 0.12 only.

海未深 2024-09-03 03:54:28
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));

输出为 22.35。
如果需要 3 位小数,请将其更改为“%.3f”。

float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));

Output is 22.35.
If you need 3 decimal points change it to "%.3f".

最丧也最甜 2024-09-03 03:54:28

很多人都提到过DecimalFormat。但如果您有最新版本的 Java,也可以使用 printf

System.out.printf("%1.2f", 3.14159D);

有关 printf 格式字符串的更多信息,请参阅格式化程序上的文档

Many people have mentioned DecimalFormat. But you can also use printf if you have a recent version of Java:

System.out.printf("%1.2f", 3.14159D);

See the docs on the Formatter for more information about the printf format string.

感性不性感 2024-09-03 03:54:28

一个简单的技巧是通过将变量乘以例如 100、四舍五入并再次除以 100.0 来生成变量的较短版本。这样你就生成了一个带有2位小数的变量:

double new_variable = Math.round(old_variable*100) / 100.0;

这个“便宜的技巧”对我来说总是足够好,并且适用于任何语言(我不是Java人,只是学习它)。

A simple trick is to generate a shorter version of your variable by multiplying it with e.g. 100, rounding it and dividing it by 100.0 again. This way you generate a variable, with 2 decimal places:

double new_variable = Math.round(old_variable*100) / 100.0;

This "cheap trick" was always good enough for me, and works in any language (I am not a Java person, just learning it).

小草泠泠 2024-09-03 03:54:28

在 Java 中打印最多 2 位小数的浮点数:

    float f = (float)11/3;
    System.out.print(String.format("%.2f",f));

输出:3.67

>使用 %.3f 最多保留三位小数。

To print a float up to 2 decimal places in Java:

    float f = (float)11/3;
    System.out.print(String.format("%.2f",f));

OUTPUT: 3.67

> use %.3f for up to three decimal places.

最笨的告白 2024-09-03 03:54:28

查看 DecimalFormat

以下是教程中的示例:

  DecimalFormat myFormatter = new DecimalFormat(pattern);
  String output = myFormatter.format(value);
  System.out.println(value + "  " + pattern + "  " + output);

如果您选择像“###.##”这样的模式,您将获得两位小数,并且我认为这些值已四舍五入。您需要查看链接以获得所需的确切格式(例如,是否需要尾随零)

Look at DecimalFormat

Here is an example from the tutorial:

  DecimalFormat myFormatter = new DecimalFormat(pattern);
  String output = myFormatter.format(value);
  System.out.println(value + "  " + pattern + "  " + output);

If you choose a pattern like "###.##", you will get two decimal places, and I think that the values are rounded up. You will want to look at the link to get the exact format you want (e.g., whether you want trailing zeros)

酒解孤独 2024-09-03 03:54:28

下面是如何在 Java 中显示具有 2 位小数的浮点数据输出的代码:

float ratingValue = 52.98929821f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsFR = Float.valueOf(decimalFormat.format(ratingValue)); // output is 52.98

Below is code how you can display an output of float data with 2 decimal places in Java:

float ratingValue = 52.98929821f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsFR = Float.valueOf(decimalFormat.format(ratingValue)); // output is 52.98
余生共白头 2024-09-03 03:54:28

DecimalFormat 上,有一个问题让我花了一个小时或更长时间 - 它以不同的方式处理双精度和浮点输入。即使更改 RoundingMode 也没有帮助。我不是专家,但认为它可以帮助像我这样的人。最终使用 Math.round 代替。
见下图:

    DecimalFormat df = new DecimalFormat("#.##");
    double d = 0.7750;
    System.out.println(" Double 0.7750 -> " +Double.valueOf(df.format(d)));
    float f = 0.7750f;
    System.out.println(" Float 0.7750f -> "+Float.valueOf(df.format(f)));
    // change the RoundingMode
    df.setRoundingMode(RoundingMode.HALF_UP);
    System.out.println(" Rounding Up Double 0.7750 -> " +Double.valueOf(df.format(d)));
    System.out.println(" Rounding Up Float 0.7750f -> " +Float.valueOf(df.format(f)));

输出:

Double 0.7750 -> 0.78
Float 0.7750f -> 0.77

Rounding Up Double 0.7750 -> 0.78
Rounding Up Float 0.7750f -> 0.77

One issue that had me for an hour or more, on DecimalFormat- It handles double and float inputs differently. Even change of RoundingMode did not help. I am no expert but thought it may help someone like me. Ended up using Math.round instead.
See below:

    DecimalFormat df = new DecimalFormat("#.##");
    double d = 0.7750;
    System.out.println(" Double 0.7750 -> " +Double.valueOf(df.format(d)));
    float f = 0.7750f;
    System.out.println(" Float 0.7750f -> "+Float.valueOf(df.format(f)));
    // change the RoundingMode
    df.setRoundingMode(RoundingMode.HALF_UP);
    System.out.println(" Rounding Up Double 0.7750 -> " +Double.valueOf(df.format(d)));
    System.out.println(" Rounding Up Float 0.7750f -> " +Float.valueOf(df.format(f)));

Output:

Double 0.7750 -> 0.78
Float 0.7750f -> 0.77

Rounding Up Double 0.7750 -> 0.78
Rounding Up Float 0.7750f -> 0.77
会发光的星星闪亮亮i 2024-09-03 03:54:28

OK - str 为浮动。

package test;

import java.text.DecimalFormat;

public class TestPtz {
  public static void main(String[] args) {
    String preset0 = "0.09,0.20,0.09,0.07";
    String[] thisto = preset0.split(",");    
    float a = (Float.valueOf(thisto[0])).floatValue();
    System.out.println("[Original]: " + a);   
    a = (float) (a + 0.01);

    // Part 1 - for display / debug
    System.out.printf("[Local]: %.2f \n", a);
    // Part 2 - when value requires to be send as it is
    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println("[Remote]: " + df.format(a));

  }
}

输出:

run:
[Original]: 0.09
[Local]: 0.10 
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)

OK - str to float.

package test;

import java.text.DecimalFormat;

public class TestPtz {
  public static void main(String[] args) {
    String preset0 = "0.09,0.20,0.09,0.07";
    String[] thisto = preset0.split(",");    
    float a = (Float.valueOf(thisto[0])).floatValue();
    System.out.println("[Original]: " + a);   
    a = (float) (a + 0.01);

    // Part 1 - for display / debug
    System.out.printf("[Local]: %.2f \n", a);
    // Part 2 - when value requires to be send as it is
    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println("[Remote]: " + df.format(a));

  }
}

Output:

run:
[Original]: 0.09
[Local]: 0.10 
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)
给我一枪 2024-09-03 03:54:28
public String getDecimalNumber(String number) {
        Double d=Double.parseDouble(number);
        return String.format("%.5f", d);
}

还要注意 NumberFormatException

public String getDecimalNumber(String number) {
        Double d=Double.parseDouble(number);
        return String.format("%.5f", d);
}

Take care of NumberFormatException as well

红玫瑰 2024-09-03 03:54:28

用于演示的简单小程序:

import java.io.*;
import java.util.Scanner;

public class twovalues {

    public static void main(String args[]) {

        float a,b;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Values For Calculation");

        a=sc.nextFloat();
        b=sc.nextFloat();

        float c=a/b;
        System.out.printf("%.2f",c);
    }
}

small simple program for demonstration:

import java.io.*;
import java.util.Scanner;

public class twovalues {

    public static void main(String args[]) {

        float a,b;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Values For Calculation");

        a=sc.nextFloat();
        b=sc.nextFloat();

        float c=a/b;
        System.out.printf("%.2f",c);
    }
}
沉睡月亮 2024-09-03 03:54:28

如果您想确保独立于语言环境,只需执行 String str = System.out.printf("%.2f", val).replace(",", ".");用户,您总是会得到/显示一个“。”作为小数点分隔符。如果您不想在稍后进行某种转换(例如 float f = Float.parseFloat(str); )时使程序崩溃,那么这是必须的

Just do String str = System.out.printf("%.2f", val).replace(",", "."); if you want to ensure that independently of the Locale of the user, you will always get / display a "." as decimal separator. This is a must if you don't want to make your program crash if you later do some kind of conversion like float f = Float.parseFloat(str);

挽你眉间 2024-09-03 03:54:28

试试这个:-

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }

Try this:-

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }
噩梦成真你也成魔 2024-09-03 03:54:28

您可以简单地使用此代码来格式化小数精度。

    double n = Math.PI;
    DecimalFormat dcf = new DecimalFormat("#.##");
    float  f = Float.parseFloat(dcf.format(n));   // float value
    double d = Double.parseDouble(dcf.format(n)); // double value
    String number = dcf.format(n);                // String value

you can simply use this code for formatting decimal precission.

    double n = Math.PI;
    DecimalFormat dcf = new DecimalFormat("#.##");
    float  f = Float.parseFloat(dcf.format(n));   // float value
    double d = Double.parseDouble(dcf.format(n)); // double value
    String number = dcf.format(n);                // String value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文