2

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?

2
  • System.out.println(speed[i]).toString().replace(".0","") ? Commented Nov 8, 2011 at 6:46
  • dreamincode.net/forums/topic/… Commented Nov 8, 2011 at 6:47

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

1

try this:

 System.out.println(String.format("%.0f", speed[i]));

Comments

0

please try:

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]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.