-1

I know that you add an L to a value if it exceeds the scope of an integer but you still have to print it as such. I understand the concept of doing it when you're just printing out a plain number.

What about when you're using a defined variable instad?

Say I have something like.

double a = 2.5;
System.out.println(a);

I want "a" to be printed out as a integer.

Thanks for any answers in advance :)

itsmetheperson
  • 77
  • 1
  • 12

3 Answers3

1

You can use Math.round for instance.

System.out.println(Math.round(a));

or you can format it as an integer as follows:

System.out.printf("%.0f%n", a);
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

cast double a to Double and use a.intValue()

Double a = new Double("2.5");
System.out.println(a.intValue());
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • Hmm all of these methods seem to work, the book I was using didn't mention any of them for some reason. I guess it expected me to ask this on stack overflow. Cheers guys. – itsmetheperson Oct 18 '14 at 16:47
0

You could use a NumberFormat. There are predefined formats available which you could use for your particular use-case.

NumberFormat format = NumberFormat.getIntegerInstance();
double a = 2.5;
System.out.println( format.format( a ) );

But it also allows to create one for more difficult output, like with a specified number of decimals. That would be much harder using Math.round or the other suggestions made here.

Robin
  • 36,233
  • 5
  • 47
  • 99