2013-02-27 49 views
0

我剛開始學習java,需要基礎幫助。我編寫了將光速轉換爲每秒千米的代碼。代碼如下所示:Java編程 - 需要插入逗號

public class LightSpeed 
{ 
    private double conversion; 

    /** 
    * Constructor for objects of class LightSpeed 
    */ 
    public LightSpeed() 
    { 
     conversion = (186000 * 1.6); //186000 is miles per second and 1.6 is kilometers per mile 
    } 

    /** 
    * Print the conversion 
    */ 
    public void conversion() 
    { 
     System.out.println("The speed of light is equal to " + conversion + " kilometers per second"); 
    } 
} 

我需要轉換爲在其中包含逗號,以便數字不會全部一起運行。而不是數字看起來像297600.0我需要它看起來像297,600.0。有人請幫忙!謝謝

+2

查找http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html – 2013-02-27 00:48:27

+2

參見[自定義格式](http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html) – 2013-02-27 00:48:55

+0

我想我知道你去哪所學校.... :) – CodyBugstein 2013-02-27 01:53:43

回答

2

您需要格式化數字。其中一種方法是在java.text中使用DecimalFormat

DecimalFormat df = new DecimalFormat("#,##0.0"); 
System.out.println("The speed of light is equal to " + df.format(conversion) + " kilometers per second"); 

另一種方式是與printf。使用逗號標誌並輸出小數點後的一位數字。這是more about the flags for printf

System.out.printf("The speed of light is equal to %,.1f kilometers per second\n", speed); 
0

轉換方法更改爲

/** 
* Print the conversion 
*/ 
public void conversion() { 
    DecimalFormat myFormatter = new DecimalFormat("###,###.##"); 
    System.out.println("The speed of light is equal to " 
      + myFormatter.format(conversion) 
      + " kilometers per second"); 
}