This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 6 years ago.
public int total;
public int likes;
public double average;
total = 5;
likes = 21;
average = likes / total;
Log.d("Average", average);
Hi, average = likes / total should return 4.2, however, its running 4.0. How can I keep it as 4.2 and not 4.0?
Calculations using only integers causes the end result to be integer, even if later you assign it to a floating point value like double. Integer division works by counting how many times the denominator can fit entirely in the numerator.
To resolve, you have to cast at least one of the 2 operands in the division so that the division is performed already in double precision (numbers inside arithmetic operations are automatically casted to a type that allow greater precision than its operands, if at least one of the operands have that precision):
average = (double)likes / total;
or
average = likes / (double) total;
Please note that this is different than average = (double) (likes / total);, which would cast the result after it has already been rounded down.
average = (double)likes / total;
Related
This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 1 year ago.
I am writing a function in which it should return the total amount that has been rounded to the nearest up pound (£). Note: the inputs are written as whole numbers without decimal places so 260 is actually £2.60 etc.
E.g.
intput: 260 -> output: 0.40
intput: 520 -> output: 0.80
total = 1.20 (because 40p + 80p)
I have written out this function:
public Double nearestPoundTotaler(List<Integer> transactions)
{
double total = 0.00;
for(Integer amount : transactions)
{
int penceAmount = amount % 100;
int penceToNearestNextPound = 100 - penceAmount;
double answer = penceToNearestNextPound / 100.0;
total = total + answer;
}
return total;
}
I have written unit tests and the logic works but the test fails since the decimal places are incorrect. E.g. if passing 260,260,260 into the method, I get the following:
expected: 1.2
but was: 1.2000000000000002
I've tried numerous ways of removing the decimal place but I haven't seemed to find a way. Also is it possible to perform this logic with the .round() methods in Java?
With the primitive type double you can't express exact numbers, due to numerical issues. Try using BigDecimal instead and the .divide() method. There you can also set the scale to 2 (2 decimal places) and the RoundingMode (usually HALF_UP)
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
When I divided the large number into a small number then the division is correct but when I write the small number to divide a large number the answer returns wrong. In my scenario, the small number always be first. here is my code this code return 7.4074074074074075E-6 but the correct result is 0.0000074074.
double itf = 0.0;
double a = 4.0;
double b = 540000;
itf = a / b;
Log.i(TAG, "savedata: outputvalue=" + itf);
BigDecimal a = new BigDecimal("4");
BigDecimal b = new BigDecimal("540000");
// 0.0000074074
a.divide(b, MathContext.DECIMAL128);
You should use a decimal type. double is outside the scope of support
This question already has answers here:
convert double into int
(1 answer)
Cast Double to Integer in Java
(19 answers)
Closed 5 years ago.
A project I have requires the movement of a player at a coordinate using getX and getY, however, I am confused on how to convert getX and getY from a double to an int so i can play them in the drawing panel.
Just casting to int will truncate the double. So you need to specify what result you really want before you decide how to get the int. For example, if the double value is 2.999, do you want your int to be 2 or 3?
If you want the closest int (3 above), then use Math.round(d) which returns a long.
You want to cast your double as an int but you need to be careful about how you cast because if you want your movement to be accurate you want values of x.5 and over to be rounded up and values below x.5 to be rounded down.
Casting will always round down so a good way to properly round is to add .5 to all of your doubles before you cast to an int.
Here are a few examples
double = 1.1
int (double) = 1
double = 1.7
int (double) = 1 \\ Note that we will likely want this to be 2
Using our method lets see how these 2 doubles would be casted
double = 1.1
double + .5 = 1.6
int (double) = 1
double 1.7 = 1.7
double + .5 = 2.2
int (double) = 2
Note that now our doubles that are above x.5 will be rounded up properly.
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 6 years ago.
The question require me to write a Java program to show the results of the following cast operator expressions:
(double) (23 / 14) + 7.65
My Code:
public class op {
public static void main(String [] args) {
int num = 23/14;
double r1 = (double) num;
double result = r1 + 7.65;
System.out.println("Results: "+ result);
}
}
I don't think I have done correctly, what are the problems of my code?
By the way, can someone tell me what are the differences between long, double, int, float? How do we know when to use these primitive data types? I read an explanation here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
but is there any 'human-version' of the explanation?
Thank you for your help.
The problem is due to the used types.
Since you divide two integers (23 and 14), the result is considered and int as well. Therefor, 23/14 = 1.642857142857143, which is truncated to fit in an int result, more specifically, 1.
result is the sum of 1 (int) and 7.65 (double). Since one of them is a double, to other is converted to the "upper" type as well (double) and the operation becomes 1.0+7.65 = 8.65.
The result is correct, because you asked the result of (double) (23 / 14) + 7.65 which means the result of casting the result of the operations in brackets to double summed with 7.65. Which is 8.65 as previously explained.
If you want to use a division using doubles, consider:
double r1 = 1.0 * 23/14;
Lets see step-by-step:
int num = 23/14; // int division of 23/14 results in 1
So, here num = 1
When you cast num to double value of r1 is setted to 1.0.
double result = r1 + 7.65; //1.0 + 7.65 = 8.65
ok, int is short term for INTEGER which are natural numbers that we use normally but with no decimal places and if your number has some value in between roughly -2 billion to +2 billion. if your range exceeds that and you still want an integer then go for long data type.
floats are for decimal values like 3.147 with a range of +10*38 to -10*38 or so, but if your range exceeds this(practically this happens rarely) go for double.
coming to the code you put here , if you divide a int by another int (like 23/14) you get only get the integer part of the answer(only '1' in 23/14=1.642...) , next when you cast it to double you get 1.0 and next you are going to add that to 7.65 which will make the ultimate answer as 8.65 hope this answers your Q....
You could change this int num = 23/14
to double num = ((double) 23)/14
or double num = (23 * 1.0)/14
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
Program 1
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
VS.
Program 2
int sum= 30
double avg =sum/4.0 // Prints lns 7.5
Is this because the '4' in program 1 is acting as a literal integer? so 30/4 would give me 7. However since this data type is a double, we need to add a .0 to end. so '7.0'
Program 2 has 4.0 which is acting as a literal double. an int/double would always give double because it more precise. so we get '7.5'. I don't understand what double data type is doing to the result though.. it really doesn't need to do anything since the conditions of the double data type are already satisfied.(have the most precise result out of the computation).
Am I wrong? I encourage you to correct me! This is how I learn.. :)
In your first example:
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
sum is an int, and 4 is also an int. Java is dividing one integer by another and getting an integer result. This all happens before it assigns the value to double avg, and by then you've already lost all information to the right of the decimal point.
Try some casting.
int sum = 30;
double avg = (double) sum / 4; // result is 7.5
OR
int sum = 30;
double avg = sum / 4.0d; // result is 7.5
This is an integer division (because it involves two integers)
int sum = 30;
double avg = (sum / 4); // result is 7
Integer division, will round down to the nearest integer.
However, this is a double division (because 4.0 is a double)
int sum= 30
double avg = (sum/4.0) // result is 7.5
This is the expected behaviour, and the conversion are all well defined. No need to guess. Take a look at the java docs about conversion.
A widening 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
In java, operations involving only integer types (int, long and so on) have integer results. This includes divisions.
Both 30 and 4 are integer values, so if you try to divide them, integer division is used.
But if you try either 30.0/4 or 30/4.0 then the result will be 7.5 because you will be using floating-point division.
The declared type of the variable avg has no influence on the result. The decimal part is lost during the division, and not when you assign the value to the variable.
Image taken from : http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html
Refer above URL for more clear explanation.
PROGRAM 1
In Java, when you do a division between two integers, the result is an integer. So when you do sum/4, the result is the integer 7. Then you assign that integer to a double variable, so that 7 turns into 7.0.
PROGRAM 2
In Java, when you do a division between an integer and a double, the result is a double. So when you do sum/4.0, the result is the double 7.5. Then you assign that to a double variable, so it's still 7.5.
So the problem is not how println prints the variables, but how division works in Java