0

我刚开始学习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。有人请帮忙!谢谢

4

2 回答 2

2

您需要格式化数字。其中一种方法是DecimalFormat在 java.text 中。

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

另一种方法是使用printf. 使用逗号标志并输出小数点后一位。这是有关 printf 标志的更多信息

System.out.printf("The speed of light is equal to %,.1f kilometers per second\n", speed);
于 2013-02-27T00:51:00.200 回答
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");
}
于 2013-02-27T00:53:18.417 回答