Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide down to decimals and not get zero in Java? [duplicate]

Tags:

java

division

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.

like image 826
batoutofhell Avatar asked Feb 07 '13 00:02

batoutofhell


People also ask

How do you show decimals when dividing in 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.

How do I limit the number of decimal places in a double Java?

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.

How do I fix decimal places in Java?

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.


3 Answers

Either cast the ints to double, or just use doubles.

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;
like image 96
Nora Powers Avatar answered Oct 06 '22 00:10

Nora Powers


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 image 42
Jason Sperske Avatar answered Oct 05 '22 22:10

Jason Sperske


Like this:

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

or this:

arrayName[0] = (double)(14/49)*100;
like image 26
xagyg Avatar answered Oct 06 '22 00:10

xagyg