java float 格式说明符

标签 java java-8 formatting printf

我想在打印 float 时实现以下格式。

Consider following example →

  • 5.55555555 → 5.5555
  • 9.0 → 9

对于第一部分,我使用了

System.out.printf("%.4f",5.5555556f);

当我将 9.0 传递到上面的同一代码段时,它会输出为 9.0000 。请帮我解决这个问题。 ✌️

最佳答案

import java.text.DecimalFormat;

public class DecimalFormatting {
    public static void main(String[] args) {
        double answer = 5.0;
        double answer1 = 5.55555555;
        DecimalFormat df = new DecimalFormat("###.####");
        System.out.println(df.format(answer));
        System.out.println(df.format(answer1));
    }
}

关于java float 格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61422590/

相关文章:

java - sonarLint:使这个匿名内部类成为 lambda

html - 为什么 HTML 要求多个空格在浏览器中显示为单个空格?

python - 在 Python 中将浮点列表转换为字符串

java - Kafka Streams : topic. Compression.type 不是已知配置

java - 设置 mime 类型

java - 使用 JTable 将 JButton 添加到框架中

从 MongoDB 返回的嵌套文档的 Java 8 Stream 实现

java - 无静态方法元工厂(OptaPlanner)

c - 如何用c语言绘制动态表格

java - 测试我的应用程序是否接受远程服务器的 SSL 证书