Java.lang.String.format() 方法

描述

java.lang.String.format(Locale l, String format, Object... args) 方法返回使用指定语言环境、格式字符串和参数的格式化字符串。


声明

以下是 java.lang.String.format() 方法的声明。

public static String format(Locale l, String format, Object... args)

参数

  • l − 这是在格式化期间应用的语言环境。 如果 l 为 null,则不应用本地化。

  • format − 这是一个格式字符串。

  • args − 这是格式字符串中格式说明符引用的参数。 如果参数多于格式说明符,则忽略多余的参数。 参数的数量是可变的,可能为零。


返回值

该方法返回一个格式化的字符串。


异常

  • IllegalFormatException − 如果格式字符串包含非法语法、与给定参数不兼容的格式说明符、给定格式字符串的参数不足或其他非法条件。

  • NullPointerException − 如果 format 为空。


示例

下面的例子展示了 java.lang.String.format() 方法的使用。

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      double piVal = Math.PI;

      /* returns a formatted string using the specified format string,
         and arguments */
      System.out.format("%f\n", piVal);
      
      /* returns a formatted string using the specified locale, format
         string and arguments */
      System.out.format(Locale.US, "%10.2f", piVal);
   }
}

让我们编译并运行上面的程序,这将产生下面的结果 −

3.141593
3.14