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.
If you need to divide two integers and get a decimal result, you can cast either the numerator or denominator to double before the operation. XResearchsource is performed. In this example, we'll cast a to double so we get a decimal result: int a = 55; int b = 25; double r = (double) a / b // The answer is 2.2.
We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places. For DecimalFormat , the default rounding mode is RoundingMode. HALF_EVEN , and we can use setRoundingMode(RoundingMode) to set a specified rounding mode.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With