2

In my app, I need to format a BigDecimal object as a String that looks like currency.

E.g. I need:

  • 45.50 to come out as $45.50
  • 3.444 to come out as $3.44
  • 0.199 to come out as $0.20
  • 6.0 to come out as $6
  • 1200 to come out as $1,200

In other words, I want to show a max of 2 decimal places and a minimum of 0 decimal places (and never just 1 decimal place).

And the rounding should be the usual way, where 0.0050 rounds to 0.01 and 0.0049 rounds to 0.

Thanks!

P.S. I think my question differs from How to print formatted BigDecimal values? because I don't ever want to show .00 for whole numbers.

2nd update:

I can't believe people closed this as a duplicate and pointed to an answer that does NOT answer my question. That type of person slowly chips away at the usefulness of StackOverflow.

Here is an answer that I've come up with, but it feels ugly, and I encourage others to share better ideas:

public static String getCasualDollarFormattedNumber(BigDecimal number)
{
    String showsTwoDecimalPlaces = NumberFormat.getCurrencyInstance().format(number);
    String zeroes = ".00";
    String lastCharacters = showsTwoDecimalPlaces.substring(Math.max(showsTwoDecimalPlaces.length() - zeroes
            .length(), 0));
    return (lastCharacters.equals(zeroes)) ? showsTwoDecimalPlaces.substring(0, 
            showsTwoDecimalPlaces.length() - zeroes.length()) : showsTwoDecimalPlaces;
}

Test:

@Test
public void testGetCasualDollarFormattedNumber()
{
    Assert.assertEquals(Replacer.getCasualDollarFormattedNumber(new BigDecimal(45.50)), "$45.50");
    Assert.assertEquals(Replacer.getCasualDollarFormattedNumber(new BigDecimal(3.444)), "$3.44");
    Assert.assertEquals(Replacer.getCasualDollarFormattedNumber(new BigDecimal(0.199)), "$0.20");
    Assert.assertEquals(Replacer.getCasualDollarFormattedNumber(new BigDecimal(6.0)), "$6");
    Assert.assertEquals(Replacer.getCasualDollarFormattedNumber(new BigDecimal(1200)), "$1,200");
}
Community
  • 1
  • 1
Ryan
  • 22,332
  • 31
  • 176
  • 357
  • I don't think so. I think you didn't read the details of my question. I updated it to make them stand out more. Thanks! – Ryan Nov 06 '13 at 00:54
  • @Ryan The change the `NumberFormatter`...The basic concept is the same – MadProgrammer Nov 06 '13 at 00:55
  • Why? It's an inconsistent requirement. It can be done but it requires extra code. Tell the designer it's simpler to just use 2 decimal places throughout. – user207421 Nov 06 '13 at 01:07
  • 1
    There's nothing builtin. Format it as already described and then truncate the last 3 characters if they're equal to `decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() + "00"` – Jim Garrison Nov 06 '13 at 01:10
  • NumberFormat formatter = NumberFormat.getCurrencyInstance(); formatter.setMinimumFractionDigits(0); formatter.setMaximumFractionDigits(2); return formatter.format(number); – Si Kelly Mar 08 '15 at 13:21

0 Answers0