Format decimal

This example shows a few examples on how to use DecimalFormat. DecimalFormat is very flexible but it important to understand the patterns defined to match your need.

Format decimal with rounding mode

@Test
public void format_decimal_with_rounding_mode () {

    double hdTv = 1229.99;

    DecimalFormat df = new DecimalFormat("###,###");
    df.setRoundingMode(RoundingMode.HALF_UP);

    assertEquals("1,230", df.format(hdTv));
}

Format decimal with trailing zeros

@Test
public void format_with_trailing_zeros () {

    double singAlongMic = 49;

    DecimalFormat df = new DecimalFormat("00.00");

    assertEquals("49.00", df.format(singAlongMic));
}

Format decimal with leading zeros

@Test
public void format_with_leading_zeros () {

    double videoGame = 49;

    DecimalFormat df = new DecimalFormat("000,000");

    assertEquals("000,049", df.format(videoGame));
}

Format decimal with commas

@Test
public void format_decimal_with_commas () {

    double expensiveLegos = 1244444;

    DecimalFormat df = new DecimalFormat("###,###");

    assertEquals("1,244,444", df.format(expensiveLegos));
}

Format decimal with dollar sign

@Test
public void format_decimal_with_dollar_sign_currency () {

    double blackFridayTVDeal = 120.9;

    DecimalFormat df = new DecimalFormat("$#.00");

    assertEquals("$120.90", df.format(blackFridayTVDeal));
}

Format decimal with optional zero

@Test
public void format_decimal_with_optional_zero () {

    double gameConsole = 229.90;

    DecimalFormat df = new DecimalFormat("#.##");

    assertEquals("229.9", df.format(gameConsole));
}