Money Format + Decimal Place Format

S

shannon

Hi,

I want to output a figure that includes two decimal places and currency
format. However, I can't get both to work. This is what i have been
working on so far. the decimal format below still returns a whole
number

outputTextArea.append( "Product 1" + "\t" + twoDigits.format(
product1 ) + "\n" +
"Product 2" + "\t" + moneyFormat.format(
product2 ) + "\n" +
 
Z

zero

Hi,

I want to output a figure that includes two decimal places and
currency format. However, I can't get both to work. This is what i
have been working on so far. the decimal format below still returns a
whole number

outputTextArea.append( "Product 1" + "\t" + twoDigits.format(
product1 ) + "\n" +
"Product 2" + "\t" +
moneyFormat.format(
product2 ) + "\n" +

Depending on what you're doing, the easiest way to get the currency
symbol is probably Currency:getSymbol(). Printing only two decimals can
be done with the String.format(String) method. An example:

private static String currencySymbol = getCurrency();

private static String getCurrency()
{
Currency curr = Currency.getInstance(Locale.getDefault());
return curr.getSymbol();
}

void doCalculation()
{
double amount = 3.98 / 1.8;

outputTextArea.append("%.2f" + currencySymbol, amount);
}

One big caveat: floating point calculations are notoriously inaccurate.
Instead of using double or float, you should consider using int or long
(and just remember that your values are off by a factor of 100), or use
BigDecimal. When using BigDecimal, you need to use a MathContext to
specify the precision. Again, an example:

private static String currencSymbol = getCurrency();

private static String getCurrency()
{
Currency curr = Currency.getInstance(Locale.getDefault());
return curr.getSymbol();
}

void doCalculation()
{
BigDecimal amount =
new BigDecimal("3.98").divide(new BigDecimal("1.8"));

BigDecimal roundedAmount = amount.round(new MathContext(2));
// implicit call to roundedAmount.toString()
outputTextArea.append(roundedAmount + currencySymbol);
}

This may seem like a lot more work, and in fact it is. However, if you
use doubles, you're likely to get inaccurate results. For an example of
what may happen, look for a discussion entitled ".09 instead of .08" in
the group comp.lang.java.help
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top