Java double to int and Other Conversions

Written by:  • Edited by: J. F. Amprimoz
Updated May 19, 2011
• Related Guides: Java

In this article, we explain what happens when Java attempts to assign a double/float value to an int type, a float value to a double variable and vice versa. We also discuss how expressions containing different numeric types (double and int, say) are evaluated in Java.

Assignment of double/float to integer types

In the article on Java Integer Arithmetic, we showed how Java performs arithmetic with integer values. We now show how it is done with floating-point numbers.

In Java, double to int (and int to double) conversions are sometimes necessary. For example, we may calculate a percentage but are interested only in the whole number part of the result. For instance, the result may be 64.37% but we don't care about the fraction. Our natural instinct is to assign the double value to an int variable.

However, Java does not let us assign a floating-point value (float or double) directly to an integer variable (byte, short, int or long).

For example, consider:

int n = 987.654321; //cannot assign double to int

long m = 3.24f; //cannot assign float to long

None of these statements is valid in Java. We can use a cast to make them valid, as in:

int n = (int) 987.654321;

long m = (long) 3.24f;

Now, 987 is assigned to n and 3 is assigned to m.

When we assign a floating-point value to an integer type, the fractional part, if any, is dropped (not rounded) and the resulting integer value is assigned. It is up to us to ensure that the integer obtained is small enough to fit in the integer type. If not, the resulting value is unpredictable.

For example, the largest byte value is 127. The statement

byte b = (byte) 300.75;

is valid and will attempt to store the value 300 in the byte variable b. Since this is too big to fit in b, the value assigned is unpredictable. In this case, the value assigned is 44.

As another example, the statement

short s = (short) 65585.36;

will store 49 in s; 65585 is too big to fit in a short variable. Here, the low-order 16 bits of 65585 (which happens to be 49) is stored in s.

Suppose the double variable d has the value 987.654321. If we want the rounded value of d (988) stored in the int variable n, we could do this with

n = (int) (d + 0.5);

If the first digit after the point in d is 5 or more, adding 0.5 would add 1 to the whole number part. If the first digit after the point is less than 5, adding 0.5 would not change the whole number part.

For example, if d is 245.75, adding 0.5 would give 246.25 and 246 would be assigned to n. But if d were 245.49, adding 0.5 would give 245.99 and 245 would be assigned to n.

Assignment between double and float

As expected, you can store a float value in a float variable and a double value in a double variable. Since float is smaller than double, Java allows you to store a float value in a double variable without any problems. However, if you try to assign a double value to a float variable, Java will complain. Consider:

double d = 987.654321;

float x = d; //this is wrong; can’t assign double to float

The second statement will give an error message since Java will recognize that precision could be lost when assigning a “bigger” value (double) to a “smaller” variable (float). However, if we are sure that that is what we want to do, we can use a cast to tell Java that we know what we are doing and are aware of the risk. We must write the statement as:

float x = (float) d;

The construct (float) is called a cast and it forces the double value d to be converted to float. A cast consists of a type name enclosed in brackets.

However, since a float variable allows only about 6 or 7 digits of precision, we should expect that the value of d may not be assigned precisely to x. Indeed, when run using one compiler, the value 987.654297 was assigned to x. When d was changed to 987654321.12345, the value assigned was 987654336.000000. In both cases, about 6 or 7 digits of precision were retained.

As an exercise, see what values would be printed using your compiler.

Recall (from the article Floating-point Numbers and Expressions) that Java automatically treats a floating-point constant as a double type, unless it is followed by f or F. We must be careful with statements such as:

float x = 3.64; //wrong

Since 3.64 is a double constant, Java will not allow us to assign it directly to a float variable. We can make the assignment valid by using either of the following:

x = (float) 3.64; //use a cast to convert to float

x = 3.64f; //write 3.64 as a float constant

Expressions with integer and floating-point values

It is quite common to use expressions involving both integer and floating-point values, for example,

a / 3 where a is float

n * 0.25 where n is int

In Java, the rule for such expressions is:

If either operand of an arithmetic operator is floating-point, the calculation is done in floating-point arithmetic.

In the first example above, the integer 3 is converted to float and the calculation is done in float. In the second example, n is converted to double (since 0.25 is double) and the calculation is done in double.

If the expression contains floating-point values only, the calculation is done in double unless both operands are float, in which case the calculation is done in float. This can be summarized as follows (click image for larger view):

Java double to int table 1
click to enlarge
Oper1 Oper2 Result

float float float

float double double

double float double

double double double

For example, if g is float, the expression g/36.0 is done in double since 36.0 is a double constant.

How do we get the exact value of an integer division, 19/5, say? We can force a double precision calculation by writing one or both constants as double, thus: 19/5.0, 19.0/5 or 19.0/5.0. We can also use a cast, as in

(double) 19 / 5

A cast allows us to force the conversion of one type to another. Here, the int 19 is cast to double, forcing 5 to be converted to double and a double precision division is performed.

However, we must be careful with a construct like

(double) (19 / 5)

since it may not do what we think. This does NOT do a floating-point division. Since both constants are integer, the expression inside the brackets is evaluated as an integer division (which discards the remainder), giving 3; this value is converted to double, giving 3.0.


Comments

Showing all 7 comments
 
HUNmal Jan 4, 2012 5:05 PM
RE: Java double to int and Other Conversions
The content go far away from the Title, so who is looking for the answer wont find it easily. I could not see ...<br>Why don't you highlight the answer of title ?
Noel Kalicharan Mar 1, 2011 7:28 PM
Response to govardhan
You raise a very interesting point. The short answer is that the operator += does an IMPLICIT conversion for you so even though Math.pow returns a double, Java converts to int for assignment to the left hand side. Note, however, that

sum = sum + Math.pow(2, 4)

would give an error.

To give a simpler example, the statement

sum += 2.5

does not give an error since Java treats it as sum = (int) (sum + 2.5)

but

sum = sum + 2.5

gives an error since we are trying to assign double to int.

Thanks for the interesting question.
govardhan Feb 25, 2011 6:09 AM
need a clarification on type casting
In my program i used

int sum=0;

sum+=Math.pow(2,4);

it is not showing any compilation error,,,, can u please explain why it is not showing any error
Noel Kalicharan Mar 7, 2010 9:31 AM
Response to jmt
Can't pass what? An exam? In that case, the examiner wants to find out if YOU can solve the problem, not if you can find someone to tell you how to solve it. What is the value of "passing" an exam this way? This is a worldwide problem with many people being granted certificates and degrees for work that others do.

Having said that, you need to convert the integer into individual parts using '%' and '/'. For example, 356 % 10 gives 6 and 356 / 100 gives 3 (integer division). You will then need to express the digits in words, e.g. '6' becomes 'six'. An array would be useful for this.
jmt Mar 7, 2010 8:23 AM
how to convert integers value into words.
pls,help me with those also...can't pass without it.. thanks..More Power to all of you...
jmt Mar 7, 2010 8:21 AM
how to sort three letters
pls sir,I'm still a beginner and I quitely need your response with regards to this matter...thak you so much...
karan kumar Aug 31, 2009 2:25 PM
java
question 1:- how we convert float value to integer value in java.

eg:-

class convert
{
public static void main(String args[])
{
float ft=Integer.parseInt(args[0]);
int nt=(ft)f;
System.out.println(nt);
}
}

plz. sir find out my programming error.........and give me my ans.
 
blog comments powered by Disqus
Email to a friend