String formatting knowledge and advanced techniques in Java, with examples and comments

Table of contents

1. Use placeholders for basic string formatting:

2. Control the precision and decimal places of floating-point numbers:

3. Format date and time:

4. Align text:

5. Format numbers with thousands separators:

6. Format currency:

7. Format percentage:

8. Basic string formatting:

9. Control the precision and decimal places of floating-point numbers:

11. Use placeholders to fill strings:

12. Align text:

13. Format integers:

14. Format floating point numbers:

15. Use commas to separate numbers:

16. Format date and time:

17. Format percentage:

18. Format boolean values:

19. Nested formatting:

20. Format currency amount:

21. Custom formatting options:

22. Format multiple objects:

23. Format the date to the specified format:

24. Align text:

25. Add signs to positive and negative numbers:

26. Format scientific notation:

27. Format hexadecimal numbers:

28. Format percentage:

29. Format date and time:

30. Format left alignment:

31. Format currency amount:

32. Format numbers according to different locales:

33. Format the date as a custom format:

34. Format the time as a custom format:

35. Format scientific notation:

36. Time zone for formatting dates and times:

37. Format numbers into different bases:


1. Use placeholders for basic string formatting:

String name = "Alice";
int age = 25;
String message = String.format("My name is %s and I am %d years old.", name, age);

Note: Use %s to represent a string and %d to represent an integer, and you can insert the value of the variable into the string.

2. Control the precision and decimal places of floating-point numbers:

double num = 3.141592653589793;
String message = String.format("The value of pi is approximately %.2f.", num);

Note: Use %.2f to format floating point numbers to two decimal places.

3. Format date and time:

import java.time.LocalDateTime;
String date = LocalDateTime.now().toString();
String message = String.format("Today's date and time is %s.", date);

Notes: Use the LocalDateTime class to get the current date and time and use %s to format it as a string.

4. Align text:

String name = "Alice";
int age = 25;
String message = String.format("Name: %-10s, Age: %d", name, age);

Note: Use %-10s to left-justify strings, and use %d to format integers.

5. Format numbers with thousands separators:

int num = 1000000;
String message = String.format("The population is %,d.", num);

Note: Use %,d to format numbers with thousands separators.

6. Format currency:

import java.util.Currency;
import java.util.Locale;
double amount = 1000.50;
Currency currency = Currency.getInstance(Locale.US);
String message = String.format("The price is %s%.2f.", currency.getSymbol(), amount);

Note: Use the Currency class to get the currency symbol and format the floating point number as currency.

7. Format percentage:

double percentage = 0.75;
String message = String.format("The discount is %.2f%%.", percentage * 100);

Note: Use %.2f%% to format floating point numbers as percentages.

8. Basic string formatting:

String name = "Alice";
int age = 25;
String message = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(message);

Note: Use %s to represent a string and %d to represent an integer, and insert the value of the variable into the string. operation result:My name is Alice and I am 25 years old.

9. Control the precision and decimal places of floating-point numbers:

double num = 3.141592653589793;
String message = String.format("The value of pi is approximately %.2f.", num);
System.out.println(message);

Note: Use %.2f to format floating point numbers to two decimal places. operation result:The value of pi is approximately 3.14.

10. Format date and time:

11. Use placeholders to fill strings:

String name = "Alice";
String message = String.format("Hello, %20s!", name);
System.out.println(message);

Comments: Use %20s to format the string as a field of length 20, right-padded with spaces. operation result:Hello, Alice!

12. Align text:

String name = "Alice";
String message = String.format("|%10s|", name);
System.out.println(message);

Comments: Use %10s to format strings into fields of length 10, padded with spaces on the left. operation result:| Alice|

13. Format integers:

int number = 42;
String message = String.format("The answer to life, the universe, and everything is %d.", number);
System.out.println(message);

Note: Use %d to format integers as strings. operation result:The answer to life, the universe, and everything is 42.

14. Format floating point numbers:

double number = 3.141592653589793;
String message = String.format("The value of pi is approximately %.4f.", number);
System.out.println(message);

Note: Use %.4f to format floating point numbers to four decimal places. operation result:The value of pi is approximately 3.1416.

15. Use commas to separate numbers:

int number = 1000000;
String message = String.format("One million is written as %,d.", number);
System.out.println(message);

Note: Use %,d to format numbers as strings with thousands separators. operation result:One million is written as 1,000,000.

16. Format date and time:

import java.time.LocalDateTime;
String dateTime = LocalDateTime.now().toString();
String message = String.format("Current date and time: %tF %tT", dateTime, dateTime);
System.out.println(message);

Note: Use %tF and %tT to format date and time in ISO 8601 format (eg: 2022-01-01 12:34:56). operation result:Current date and time: 2022-01-01 12:34:56

17. Format percentage:

double percentage = 0.75;
String message = String.format("The discount is %.2f%%.", percentage * 100);
System.out.println(message);

Note: Use %.2f%% to convert decimals to percentages and keep two decimal places. operation result:The discount is 75.00%.

18. Format boolean values:

boolean isTrue = true;
String message = String.format("The value of the boolean is %b.", isTrue);
System.out.println(message);

Note: Use %b to format booleans as strings. operation result:The value of the boolean is true.

19. Nested formatting:

int number = 42;
String message = String.format("The answer to life, the universe, and everything is %d, which is %.2f%% of %s.", number, (double)number / 100, "100");
System.out.println(message);

Note: Multiple placeholders are nested within the format string. operation result:The answer to life, the universe, and everything is 42, which is 0.42% of 100.

20. Format currency amount:

import java.text.NumberFormat;
double amount = 1234.56;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
String message = String.format("The total amount is %s.", currencyFormatter.format(amount));
System.out.println(message);

Note: Use the NumberFormat class and the getCurrencyInstance() method to format numbers as currency amounts. operation result:The total amount is $1,234.56.

21. Custom formatting options:

String name = "Alice";
int age = 25;
String message = String.format("Hello, %s! You are %02d years old.", name, age);
System.out.println(message);

Note: Use %02d to format integers as two digits with leading zeros. operation result:Hello, Alice! You are 25 years old.

22. Format multiple objects:

int apples = 5;
int oranges = 3;
String message = String.format("I have %d apples and %d oranges.", apples, oranges);
System.out.println(message);

Note: Use multiple placeholders in the format string and provide the corresponding arguments in order. operation result:I have 5 apples and 3 oranges.

23. Format the date to the specified format:

import java.time.LocalDate;
String date = LocalDate.now().toString();
String message = String.format("Today's date is %s.", date);
System.out.println(message);

Note: Use %s to format dates as strings. operation result:Today's date is 2022-01-01.

24. Align text:

String name = "John";
String message = String.format("Hello, %10s!", name);
System.out.println(message);

Note: Use %10s to right-justify the string and pad spaces on the left (if the string is less than 10 characters). operation result:Hello, John!

25. Add signs to positive and negative numbers:

int positiveNumber = 42;
int negativeNumber = -42;
String message = String.format("Positive: %+d, Negative: %+d", positiveNumber, negativeNumber);
System.out.println(message);

Note: Use %+d to display the sign (+/-) for both positive and negative numbers. operation result:Positive: +42, Negative: -42

26. Format scientific notation:

double number = 1.23456789E10;
String message = String.format("Scientific notation: %.2e", number);
System.out.println(message);

Note: Use %.2e to format numbers in scientific notation and specify the number of digits after the decimal point. operation result:Scientific notation: 1.23e+10

27. Format hexadecimal numbers:

int number = 255;
String message = String.format("Hexadecimal: %x", number);
System.out.println(message);

Note: Use %x to format integers as hexadecimal. operation result:Hexadecimal: ff

28. Format percentage:

double percentage = 0.75;
String message = String.format("Percentage: %.2f%%", percentage * 100);
System.out.println(message);

Note: Use %.2f to format decimals as percentages, and multiply by 100 to convert to percentages. operation result:Percentage: 75.00%

29. Format date and time:

import java.time.LocalDateTime;
LocalDateTime dateTime = LocalDateTime.now();
String message = String.format("Current date and time: %tF %tT", dateTime, dateTime);
System.out.println(message);

Note: Use %tF and %tT to format the date and time to the specified format. operation result:Current date and time: 2022-01-01 12:34:56

30. Format left alignment:

String name = "Alice";
String message = String.format("Hello, %-10s!", name);
System.out.println(message);

Note: Use %-10s to left-justify the string and pad spaces on the right if the string is less than 10 characters long. operation result:Hello, Alice !

31. Format currency amount:

import java.text.NumberFormat;
double amount = 12345.67;
String message = String.format("Amount: %s", NumberFormat.getCurrencyInstance().format(amount));
System.out.println(message);

Note: Use the getCurrencyInstance() method of the NumberFormat class to get an instance of the formatted currency and format the amount in currency format. operation result:Amount: $12,345.67

32. Format numbers according to different locales:

import java.text.NumberFormat;
double amount = 12345.67;
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.FRENCH);
String message = String.format("Amount: %s", numberFormat.format(amount));
System.out.println(message);

Note: Use the getNumberInstance() method of the NumberFormat class to get an instance of a specific locale and format the number to that locale's format. Running results (in the French environment):Amount: 12 345,67

33. Format the date as a custom format:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String message = String.format("Custom date format: %s", date.format(formatter));
System.out.println(message);

Note: Use the ofPattern() method of the DateTimeFormatter class to create an instance of a custom date format and format the date to that custom format. operation result:Custom date format: 01/01/2022

34. Format the time as a custom format:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
LocalTime time = LocalTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String message = String.format("Custom time format: %s", time.format(formatter));
System.out.println(message);

Note: Use the ofPattern() method of the DateTimeFormatter class to create an instance of a custom time format and format the time to that custom format. operation result:Custom time format: 12:34:56

35. Format scientific notation:

double number = 12345.6789;
String message = String.format("Scientific notation: %.2e", number);
System.out.println(message);

Note: Use %.2e to format numbers in scientific notation and specify the number of digits after the decimal point. operation result:Scientific notation: 1.23e+04

36. Time zone for formatting dates and times:

import java.time.ZonedDateTime;
ZonedDateTime dateTime = ZonedDateTime.now();
String message = String.format("Date and time with timezone: %tF %tT %tz", dateTime, dateTime, dateTime);
System.out.println(message);

Note: Use %tF, %tT, and %tz to format date, time, and time zone information into the specified format. operation result:Date and time with timezone: 2022-01-01 12:34:56 +0800

37. Format numbers into different bases:

int number = 255;
String message = String.format("Binary: %s, Octal: %s", Integer.toBinaryString(number), Integer.toOctalString(number));
System.out.println(message);

Note: Use the toBinaryString() and toOctalString() methods of the Integer class to format numbers in binary and octal. operation result:Binary: 11111111, Octal: 377

Guess you like

Origin blog.csdn.net/zh6526157/article/details/132480138