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

最佳答案

您需要格式化数字。一种方法是使用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);

09-11 13:14