views:

135

answers:

2

In my code there are some calls to a method that set the values of some JTextFields

fields[7].setText(String.valueOf(inv.get(currentDisplay).feeValue()));

This works and it is doing what I want but the values look like this 81.65849999999999

How would I make the output of String.valueOf look like the normal output of

System.out.printf( "$%,.2f", getDollarAmount() )
+1  A: 

Use this class. Here is an example that I think will help here. Here is the code from the example link:

import java.text.NumberFormat;

public class Mortgage {
  public static void main(String[] args) {
    double payment = Math.random() * 1000;
    System.out.println("Your payment is ");
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    System.out.println(nf.format(payment));
  }
}

My only caution is that it does do rounding - there are methods you can play with to adjust this though...

javamonkey79
NumberFormat did the job. Thanks!!
lazfish
Happy to help, yw :)
javamonkey79
+1  A: 

Use:

locale = Locale.CANADA;
String str = NumberFormat.getCurrencyInstance(locale).format(123.45);
//output: $123.45

Alternate:

NumberFormat formatter = new DecimalFormat("'$'###.00");
String str = formatter.format(getDollarAmount());

Reference: Formatting a Number Using a Custom Format

OMG Ponies
I am not Canadian!!!Thanks for the help :)
lazfish