java打印出一个双数组
我有一个数组,里面有一些双值:java打印出一个双数组,java,Java,我有一个数组,里面有一些双值: private double speed[] = {50, 80, 120, 70.3}; public void printSpeed() { for(int i = 0; i<=speed.length-1; i++ ) { System.out.println(speed[i]); } } output 50.0 80.0 12.0 70.3 wanted output 50 80 12 70.3 privat
private double speed[] = {50, 80, 120, 70.3};
public void printSpeed() {
for(int i = 0; i<=speed.length-1; i++ ) {
System.out.println(speed[i]);
}
}
output
50.0
80.0
12.0
70.3
wanted output
50
80
12
70.3
private double speed[]={50,80,120,70.3};
公共空间打印速度(){
对于(int i=0;i<P)>首先要注意的是:最终值将不完全是70.3,因为在双< /代码>中不能精确表示。如果精确的十进制值对您很重要,则应考虑使用<代码> BigDecimal < /C> >。< /P>
听起来您需要一个NumberFormat
,它省略了后面不重要的数字:
import java.text.*;
public class Test {
public static void main(String[] args) {
// Consider specifying the locale here too
NumberFormat nf = new DecimalFormat("0.#");
double[] speeds = { 50, 80, 120, 70.3 };
for (double speed : speeds) {
System.out.println(nf.format(speed));
}
}
}
(顺便说一句,我强烈建议您为具有类型信息的数组声明保留[]
,double[]speed
,而不是double[]
。它是更惯用的Java,它将所有类型信息放在一个位置。)尝试以下方法:
System.out.println(String.format("%.0f", speed[i]));
请尝试:
for(int i = 0; i < speed.length; i++ ) {
long l = (long)speed[i];
if(l == speed[i]) {
System.out.println(l);
} else {
System.out.println(speed[i]);
}
}
for(int i=0;i
System.out.println(速度[i]).toString().replace(“.0”,”)?