double[] arrayName = new double[10];
arrayName[0] = (14/49)*100;
Trying to get percentage of two numbers, 14 / 49, and add results to an array. All it returns is 0.0. Same thing if I use float instead of double. New to Java.
double[] arrayName = new double[10];
arrayName[0] = (14/49)*100;
Trying to get percentage of two numbers, 14 / 49, and add results to an array. All it returns is 0.0. Same thing if I use float instead of double. New to Java.
Either cast the int
s to double
, or just use double
s.
For example:
double[] arrayName = new double[10];
resultValue[0] = (14.0/49.0)*100;
or:
double[] arrayName = new double[10];
resultValue[0] = ((double)14/49)*100;
How you see it:
(double/double)*double
How the JVM sees it
(int/int)*int
From the the JLS. int to double is a widening conversion. From §5.1.2:
Widening primitive conversions do not lose information about the overall magnitude of a numeric value.
[...]
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).
If you replace one of those with a double literal (like adding .0
or cast one of them to double
and you should get the result you expect.
Like this:
arrayName[0] = (14/49)*100.0; // put ".0" after any of the numbers
or this:
arrayName[0] = (double)(14/49)*100;
At least one of your values should be a 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;
As many others have pointed, you just have to set the constants as doubles:
arrayName[0] = (14*100)/49.0;
This way, you convert only the last computation to double instead of the beginning , and reduce the number of floating point calculations.
Btw, if you wish, you can also have the result as an integer by using the same method of swapping the order and use multiplication before division, for example: 14*100/49 instead of (14/49)*100.