温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中如何格式化输出Double双精度

发布时间:2025-11-03 10:05:22 来源:亿速云 阅读:108 作者:小樊 栏目:编程语言

在Java中,可以使用String.format()方法和System.out.printf()方法来格式化输出Double双精度数值。这两种方法都使用了相同的格式化字符串。

以下是一些常用的格式化选项:

  1. 保留小数点后n位:%.nf,其中n是你想要保留的小数位数。
  2. 固定小数点表示法:%f。
  3. 科学计数法表示法:%e。
  4. 百分比表示法:%%。

示例:

public class FormatDouble {
    public static void main(String[] args) {
        double num1 = 123.456789;
        double num2 = 0.0012345;

        // 保留两位小数
        System.out.println(String.format("%.2f", num1)); // 输出:123.46
        System.out.println(String.format("%.2f", num2)); // 输出:0.00

        // 固定小数点表示法
        System.out.println(String.format("%f", num1)); // 输出:123.456789
        System.out.println(String.format("%f", num2)); // 输出:0.001235

        // 科学计数法表示法
        System.out.println(String.format("%e", num1)); // 输出:1.234568e+02
        System.out.println(String.format("%e", num2)); // 输出:1.234560e-03

        // 百分比表示法
        System.out.println(String.format("%n%%", num1)); // 输出:12345.678900%
        System.out.println(String.format("%n%%", num2)); // 输出:0.123456%
    }
}

注意:在格式化字符串中,%字符需要使用%%来表示。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手