Oct 01

Either use the format() method of the SimpleDateFormat class, or the (static) format() method of the String class.


DateFormat dateFormat = new SimpleDateFormat("hhmmddMMyy");
Date today = new Date();
String formatted = dateFormat.format(today);
String formatted2 =
   String.format("%<tH%<tM%<tS%tY%<tm%<td", today);

written by objects \\ tags: , , ,

Oct 01

That’s a job for the BigDecimal class


public static String formatToSignificant(double value,
   int significant)
{
   MathContext mathContext = new MathContext(significant,
      RoundingMode.DOWN);
   BigDecimal bigDecimal = new BigDecimal(value,
      mathContext);
   return bigDecimal.toPlainString();
} 

written by objects \\ tags: ,

Sep 25

Create an instance of DecimalFormat with the required format and use its format() method to format the double value. See the DecimalFormat javadoc for details on specifying format.


double d = 1.23456789;

// Use 2 decimal places

NumberFormat numberFormat =
   new DecimalFormat("#.##");

String s = numberFormat.format(d);
System.out.println(s);   // Outputs: 1.23 

written by objects \\ tags: , ,