2009-09-07 40 views
0

在我的代碼有該設置一些JTextFields將格式(錢)用的setText(將String.valueOf)

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

這個工作,它是做我想要什麼,但值的方法調用的一些值這個樣子81.65849999999999

我怎麼會做出將String.valueOf的輸出看起來像

System.out.printf("$%,.2f", getDollarAmount()) 

回答

3

使用this類的正常輸出。以下是我認爲有助於here的一個示例。下面是來自例子鏈接代碼:

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

我唯一的警告是,它並做倒圓的 - 有方法,你可以玩到,雖然調整此...

+0

NumberFormat完成了這項工作。謝謝!! – gooddadmike 2009-09-07 01:20:37

+0

樂意幫忙,yw :) – javamonkey79 2009-09-07 16:39:30

1

用途:

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

備選:

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

參考:Formatting a Number Using a Custom Format

+0

我不是加拿大人!!! 感謝您的幫助:) – gooddadmike 2009-09-07 01:30:15