There are times when you need to present a stored value in a different format . . .
Real number example – 8.987578. Here you may prefer to say 8.99
Date example – “2018-1-1”. Here you may prefer to say “1 January 2018”
Java has a number of String formatting methods that do not alter the original value but allows you to express the value in a different format.
Shown below are two examples i.e. one that allows you to format a real number differently and another that allows you to format a date differently. Both of these format methods allow you to define the format using a String parameter.
==============================================================
// Formatting real numbers and dates for output in another format. // Using String as a parameter to define an output format. // New output format does not affect the original value in any way.
// // Default date format is yyyy-MM-dd // Other formats include . . . // "yyyy/M/dd" Month as a single digit. // "dd-MMM-yyyy" Month as 3 letters. // "dd-MMMM-yyyy" Month in full as letters. // "dd-MM-yy"
import java.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.time.*;
public class Formatting {
public static void main (String[]args) {
// Define the desired format as a String and apply the format
DecimalFormat d = new DecimalFormat("0.000");
double theDouble = 45.78864469;
System.out.println(d.format(theDouble));
System.out.println(theDouble);
// Define the desired format as a String and apply the format
DateTimeFormatter formatDate = DateTimeFormatter.ofPattern("dd-MMMM-yyyy");
LocalDate localDate = LocalDate.of(2021, 11, 19);
String localDateString = formatDate.format(localDate);
System.out.println();
System.out.println(localDateString);
System.out.println(localDate);
}
}
===============================================================
OUTPUT
45.789 45.78864469
19-November-2021
2021-11-19