我刚刚开始学习 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。请有人帮忙!谢谢
最佳答案
您需要格式化该数字。其中一种方法是使用 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
。使用逗号标志并输出小数点后一位数字。这是more about the flags for printf .
System.out.printf("The speed of light is equal to %,.1f kilometers per second\n", speed);
关于Java编程-需要插入逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102228/