Java编程 - 需要插入逗号

时间:2013-02-27 00:45:53

标签: java number-formatting

我刚开始学习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 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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");
}