Question:
help in programming convert double to integer?
Jomar
2011-09-14 01:27:32 UTC
System.out.println("Enter a double value :");
double d=Double.parseDouble(as.readLine()); int x=(int)d;

System.out.println("equals :"+x);


and if i Enter for example 10.5 it will output 11...please help ..
Four answers:
Nitin Verma
2011-09-14 02:02:23 UTC
Looks like you need to round the double



Ref: http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#round%28double%29



double to long

float to int



You can just cast the output of int x = (int) Math.round(d);



You may suffer an overflow but I assume you know the limits of int as it is just 32 bits.
modulo_function
2011-09-14 09:01:22 UTC
I used Scanner and so had to change your readLine() to nextLine() but it doesn't matter. The parseDouble(..) method takes a string.



I get an output of 10 which is expected since a (int) cast just truncates 10.5 to 10.



Why would you get 11? There's something wrong with what you're telling us.



+add

I misunderstood your question. You want it to round the number right? That's easy, just add 0.5 to the double before casting:



int x = (int)(d + 0.5);



Then it will round according to the usual rule printing 11
MrMister
2011-09-14 08:54:57 UTC
I think you need something like this....



double myDouble = 420.5;



int i = (int)myDouble;
Vaibhav
2011-09-14 12:20:42 UTC
Use Math.round()

int x=(int)Math.round(d);


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...