How to split to decimals and not get null in Java?

double[] arrayName = new double[10]; 
arrayName[0] = (14/49)*100;

Trying to get the percentage of two numbers, 14/49, and add the results to the array. Everything returns - 0.0. Same thing if I use float instead of double. New in Java.

+5
source share
5 answers

Either cancel intto double, or just use doubles.

For instance:

double[] arrayName = new double[10]; 
resultValue[0] = (14.0/49.0)*100;

or

double[] arrayName = new double[10]; 
resultValue[0] = ((double)14/49)*100;
+9
source

As you see it:

(double/double)*double

As the JVM sees

(int/int)*int

From JLS . int double is an expanding conversion. From §5.1.2 :

Extension primitive transformations do not lose information about the total value of a numerical value.

[...]

int long , , . , IEEE 754 (§4.2.4).

(, .0 double), .

+4

double:

double[] arrayName = new double[10]; 
arrayName[0] = (14d/49d)*100;
// or...
// arrayName[0] = (14d/49)*100;
// or...
// arrayName[0] = (14/49d)*100;
// or...
// arrayName[0] = (14.0/49)*100;
// or...
// arrayName[0] = (14/49.0)*100;
// or...
// arrayName[0] = (14/(double)49)*100;
// or...
// arrayName[0] = ((double)14/49)*100;
// or...
// arrayName[0] = ((double)14/(double)49)*100;
+3

:

arrayName[0] = (14/49)*100.0; // put ".0" after any of the numbers

:

arrayName[0] = (double)(14/49)*100;
+2

, :

arrayName[0] = (14*100)/49.0;

Thus, you only convert the last calculation to double instead of the beginning and reduce the number of floating point calculations.

Btw, if you want, you can also get the result as an integer using the same method of exchanging order and use multiplication before division, for example: 14 * 100/49 instead of (14/49) * 100.

+2
source

All Articles