美文网首页
String.format()详细用法

String.format()详细用法

作者: 因为我的心 | 来源:发表于2022-11-15 16:04 被阅读0次

1、 String.format()字符串常规类型格式化的两种重载方式

  • 1、format(String format, Object… args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串
  • 2、format(Locale locale, String format, Object… args) 使用指定的语言环境,制定字符串格式和参数生成格式化的字符串
    注意:Java应用语言国际化处理时,使用Locale.getDefault()。
  • 本机Windows机器如下方式实现:
    (1)可通过修改操作系统的语言设置。
    (2)Java启动参数添加:-Duser.language=en -Duser.country=US。
  • linux可通过修改系统语言来实现。`

2、 字符类型和整数类型的格式化

image.png

3、代码展示

       var str:String=String.format("Hi,%s", "小智")
        //Hi,小智
        System.out.println(str)
        //Java应用语言国际化处理时,使用Locale.getDefault()
        var str2:String=String.format(Locale.getDefault(),"Hi,%s", "小刚")
        //Hi,小刚
        System.out.println(str2)

        str=String.format("Hi,%s %s %s", "小智","是个","Java开发工程师");
        //Hi,小智 是个 Java开发工程师
        System.out.println(str);
        //字母c的大写是:C
        System.out.printf("字母c的大写是:%c %n", 'C');
        //100的一半是:50
        System.out.printf("100的一半是:%d %n", 100/2);
        //100的16进制数是:64
        System.out.printf("100的16进制数是:%x %n", 100);
        //100的8进制数是:144
        System.out.printf("100的8进制数是:%o %n", 100);
        //50元的书打8.5折扣是:42.500000 元
        System.out.printf("50元的书打8.5折扣是:%f 元%n", 50*0.85);
        //这里表示小数点后面保留两位小数
        //50元的书打8.5折扣是:42.50元
        System.out.printf("50元的书打8.5折扣是:%.2f 元%n", 50*0.85);
        //上面价格的16进制数是:0x1.54p5
        System.out.printf("上面价格的16进制数是:%a %n", 50*0.85);
        //上面价格的指数表示:4.250000e+01
        System.out.printf("上面价格的指数表示:%e %n", 50*0.85);
        //上面价格的指数和浮点数结果的长度较短的是:42.5000
        System.out.printf("上面价格的指数和浮点数结果的长度较短的是:%g %n", 50*0.85);
        //上面的折扣是85%
        System.out.printf("上面的折扣是%d%% %n", 85);
        //字母A的散列码是:41
        System.out.printf("字母A的散列码是:%h %n", 'A');

4、日期转换符

image.png
        Date date=new Date();
        //c的使用 (全部日期和时间信息:星期五 三月 12 09:24:34 CST 2021)
        System.out.printf("全部日期和时间信息:%tc%n",date);
        //f的使用 (年-月-日格式:2021-03-12)
        System.out.printf("年-月-日格式:%tF%n",date);
        //d的使用 (月/日/年格式:03/12/21)
        System.out.printf("月/日/年格式:%tD%n",date);
        //r的使用 (HH:MM:SS PM格式(12时制):09:24:34 上午)
        System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date);
        //t的使用 (HH:MM:SS格式(24时制):09:24:34)
        System.out.printf("HH:MM:SS格式(24时制):%tT%n",date);
        //R的使用 (HH:MM格式(24时制):09:24)
        System.out.printf("HH:MM格式(24时制):%tR",date);

相关文章

网友评论

      本文标题:String.format()详细用法

      本文链接:https://www.haomeiwen.com/subject/ydfexdtx.html