Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide two long variables in java [duplicate]

Sorry for the basic question, I have to divide the long variable by another long variable, but it returns 0. Can any one help

long a = 3004230; long b =  6793368; long c = (a/b)*100; 
like image 684
Arulmurugan Avatar asked Jul 09 '14 10:07

Arulmurugan


People also ask

How do you divide a long number in Java?

Java Long divideUnsigned() Method. The divideUnsigned() method of Java Long class is used to return the unsigned quotient by dividing the first argument with the second argument such that each argument and the result is treated as an unsigned argument.

How do you divide two variables in Java?

// Divide a literal by a literal; result is 5 int result = 10 / 2; // Divide a variable by another variable; result is 3 int a = 15; int b = 5; int result = a / b; When dividing integer types, the result is an integer type (see the previous chapter for the exact data type conversions for mathematical operations).


2 Answers

Literal Values and Literal Arithmatic

There are a couple of issues with that code. Firstly, non-floating point literal values are of type int by default and so 3004230 in your code is an int. To explicitly declare it a long use 3004230L instead.

Also, all arithmetic done with non-floating point literals returns an int result unless one of the variables are casted specifically to a floating point type such as float or double. As such (a/b)*100 is less than 1, and therefore is truncated down to 0 (the floating point values are just cut off). Also, even if it did return the same result you are trying to store it in a long which can not store floating point values.

So, you should do something like the following to get the real result.

long a = 3004230L; // Use the L notation to declare this literal a long. long b = 6793368L; double c = ((double)a/b)*100; /* casting one of the variables to (double) means the result will not be 0 */ 

I hope this helps.

like image 84
Rudi Kershaw Avatar answered Oct 14 '22 21:10

Rudi Kershaw


final long a = 3004230; final long b = 6793368; final double c = ((double) a / b) * 100; 

=> c = 44.22298335670907

like image 25
Cengiz Avatar answered Oct 14 '22 23:10

Cengiz