Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java print out a double array

Tags:

java

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?

like image 947
hkguile Avatar asked Jun 12 '26 13:06

hkguile


2 Answers

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.)

like image 145
Jon Skeet Avatar answered Jun 15 '26 02:06

Jon Skeet


try this:

 System.out.println(String.format("%.0f", speed[i]));
like image 28
James.Xu Avatar answered Jun 15 '26 03:06

James.Xu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!