java float格式指定器

问题描述 投票:0回答:1

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

请看下面的例子 →

  • 5.55555555 → 5.5555
  • 9.0 → 9

第一部分我用了

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

当我把9.0传给上面同样的代码段时,它给出的输出为 9.0000 . 请帮我解决这个问题。✌️

java formatting printf
1个回答
1
投票
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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.