String.format()的用法

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

format(String format, Object… args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串。
format(Locale locale, String format, Object… args) 使用指定的语言环境,制定字符串格式和参数生成格式化的字符串。

常用的转化符

 

 

代码示例:

    String str = null;  
    str=String.format("Hi,%s", "siri");   
    System.out.println(str);   // Hi,siri
    
    str=String.format("Hi,%s %s", "siri","我在");            
    System.out.println(str);                 // Hi,siri 我在 
              
    System.out.printf("字母c的大写是:%c %n", 'C');  // 字母c的大写是:C  
    System.out.printf("布尔结果是:%b %n", "小超".equal("帅哥"));  // 布尔的结果是:false   
    System.out.printf("100的一半是:%d %n", 100/2);  // 100的一半是:50   
    System.out.printf("100的16进制数是:%x %n", 100);  // 100的16进制数是:64   
    System.out.printf("100的8进制数是:%o %n", 100);  // 100的8进制数是:144   
    System.out.printf("50元的书打8.5折扣是:%f 元%n", 50*0.85);  //50元的书打8.5折扣是:42.500000 元  
    System.out.printf("上面价格的16进制数是:%a %n", 50*0.85);  //上面价格的16进制数是:0x1.54p5   
    System.out.printf("上面价格的指数表示:%e %n", 50*0.85);  //上面价格的指数表示:4.250000e+01   
    System.out.printf("上面价格的指数和浮点数结果的长度较短的是:%g %n", 50*0.85);  //上面价格的指数和浮点数结果的长度较短的是:42.5000 
    System.out.printf("上面的折扣是%d%% %n", 85);  //上面的折扣是85% 
    System.out.printf("字母A的散列码是:%h %n", 'A');    //字母A的散列码是:41   

 

posted @ 2022-10-18 09:27  明天,你好啊  阅读(40)  评论(0编辑  收藏  举报