Feb 23

Decimal format uses BigDecimal.ROUND_HALF_EVEN and prior to 1.6 this cannot be changed.
In 1.6 a setRoundingMethod() was added to allow the rounding strategy to be changed.

DecimalFormat df = NumberFormat.getNumberInstance();
df.setRoundingMode(1, RoundingMode.HALF_UP);
String formatted = df.format(12.345);

If you need an alternate rounding strategy prior to 1.6 then you need to use BigDecimal to do your formatting.

double d = 123.45;
BigDecimal bd = new BigDecimal(d);
bd.setScale(1, BigDecimal.ROUND_HALF_UP);
String formatted = bd.toString();

written by objects \\ tags: , , , ,

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: ,