Pervaiz Ahmed
Pervaiz Ahmed

Reputation: 1

how to convert data types of variables in java

I have a problem that I want to display double type data in integer type when there is no any . (dot) in data or there is . (dot) in data then display float type data. In java

i.e.

double a=2;
double b=4;
double sum=a+b;
sum=6.0

but i want sum=6

OR
double a=2.1;
double b=4;
double sum=a+b;
sum=6.1

but i want sum=6

Upvotes: 0

Views: 102

Answers (5)

mumenh
mumenh

Reputation: 17

use casting in Java to print out your result. For more information , please see

http://howtoprogramwithjava.com/java-cast/

Upvotes: 0

obelix
obelix

Reputation: 900

Your sum variable should be casted into an integer... Try this:

double a=2.1;
double b=4;
double sum=a+b;
int sumInt=(int)sum;

Upvotes: 0

Visionstar
Visionstar

Reputation: 365

you have to cast your variable to an integer: try it out like this:

System.out.println((int)(66.314));
System.out.println((int)(sum));

Upvotes: 0

Kumar Abhinav
Kumar Abhinav

Reputation: 6675

use a cast...

(int)double or else you can declare an int variable and assign that to double.You need to add cast as there is loss of precision

int value =(int)double_val

Upvotes: 1

Mureinik
Mureinik

Reputation: 312219

You can use the cast syntax. Note that this would raise a warning in most compilers/IDEs, as you are losing precision here:

int sum = (int)(a + b);

Upvotes: 2

Related Questions