3

I have an array of double-type numbers {1.0, 2.3, 3.45, 7.8, 9.0, 5.0}. When outputting the numbers, I want to have those with decimal of 0 to show up like an integer: for example, 1.0 => 1, 9.0 => 9.

In java, how do you do this easily? thanks

5
  • 2
    Look up the NumberFormat class. Commented Sep 16, 2013 at 18:12
  • 1
    DecimalFormat or if it's console System.printf() like in c Commented Sep 16, 2013 at 18:13
  • stackoverflow.com/questions/2683324/java-char-array-to-int Try this link to a question asked before Commented Sep 16, 2013 at 18:21
  • DecimalFormat df = new DecimalFormat("#.##"); df.parse(3.0D); Commented Sep 16, 2013 at 18:22
  • @nachokk An alternate to System.printf() for non-console stuff is String.format(). Commented Sep 16, 2013 at 19:04

1 Answer 1

7

Not using any libraries I'd suggest:

public static String parse(double num) {
    if((int) num == num) return Integer.toString((int) num); //for you, StackOverflowException
    return String.valueOf(num); //and for you, Christian Kuetbach
}

Casting a double to int will cut off decimal places.

Feel free to convert the number to a string in whatever way you please ;)

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

3 Comments

Would you please use Integer.toString? In my opinion it's better style than ""+anything...
I would use String.valueOf() :)
Or that one, but String.valueOf calls Integer.toString internally, so it's one method call less. Not worth worrying about though...

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.