Java打印格式化小数

huangapple go评论63阅读模式
英文:

Java Print formatting decimal

问题

System.out.println("\n 两个不同的复数根存在:root1 = " +
                   String.format("%.4f", x1) + " + " + imaginary + "i 和 root2 = " +
                   String.format("%.4f", x2) + " - " + imaginary + "i");

在这里是我尝试格式化的二次公式

else if (disc < 0) {
    x1 = x2 = -b / (2 * a);
    imaginary = Math.sqrt(-disc) / (2 * a);
    System.out.format("%.3f%n 两个不同的复数根存在:root1 = " +
                      String.format("%.4f", x1) + " + " + imaginary + " 和 root2 = " +
                      String.format("%.4f", x2) + " - " + imaginary);

}
英文:

How can I format the following to 4 decimal places. I wasn't able to use System.out.format(&quot;****&quot;) or System.out.printf(&quot;****&quot;)

System.out.println(&quot;\n Two Distinct Complex Roots Exists: root1 = &quot; +
                    x1 + &quot; + &quot; + imaginary + &quot;i and root2 = &quot; + x2 +&quot; - &quot; +imaginary + &quot;i&quot;);

here is the quadratic formula that I'm trying to format

else if (disc &lt; 0) {
            x1 = x2 = -b / (2 * a);
            imaginary = Math.sqrt(-disc) / (2 * a);
            System.out.format(&quot;%.3f%n Two Distinct Complex Roots     Exists: root1 = &quot; +
                    x1 + &quot; + &quot; + imaginary + &quot; and root2 = &quot; + x2 +&quot; - &quot; +imaginary);

        }

答案1

得分: 2

DecimalFormat df = new DecimalFormat("#.####");

System.out.println(df.format(d));
英文:
DecimalFormat df = new DecimalFormat(&quot;#.####&quot;);

System.out.println(df.format(d));

huangapple
  • 本文由 发表于 2020年10月1日 12:44:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64149207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定