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");
}