i have an array with some double value inside:
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
How to do print the exactly string of the array?
One thing to note to start with: the final value will not be exactly 70.3, as that can't be exactly represented in a double. If exact decimal values are important to you, you should consider using BigDecimal instead.
It sounds like you want a NumberFormat which omits trailing insignificant digits:
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));
}
}
}
(As an aside, I would strongly advise you to keep the [] for array declarations with the type information - double[] speeds instead of double speeds[]. It's much more idiomatic Java, and it puts all the type information in one place.)
try this:
System.out.println(String.format("%.0f", speed[i]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With