What are the functions of formatting in Java?

In Java, format is a method of the String class used for formatting strings. It provides the following functionalities:

  1. Format numbers: You can use formatting symbols to specify the format of numbers (such as decimal places, thousand separators, etc.).
  2. Format date and time: You can use formatting symbols to specify the format of the date and time, such as year, month, day, hour, minute, second, etc.
  3. Format currency: You can specify the format of the currency using formatting symbols (such as currency symbol, decimal places, etc.).
  4. String formatting: You can use formatting symbols to specify the format of a string (such as padding characters, alignment, etc.).
  5. Format percentage: You can use formatting symbols to represent numbers in percentage form (such as multiplying by 100 and adding the percentage symbol).

For example, here is an example of formatting numbers and dates using the format method:

Format numbers:

int num = 1000;
String formattedNum = String.format("%,d", num);
System.out.println(formattedNum); // 输出: 1,000

Format date:

import java.util.Date;
import java.text.SimpleDateFormat;

Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(now);
System.out.println(formattedDate); // 输出: 当前日期和时间的格式化字符串

Please note that in the example above, the format method returns a formatted string without modifying the original string.

bannerAds