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.
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));
This question already has answers here:
Retain precision with double in Java
(24 answers)
Is floating point math broken?
(31 answers)
Closed 4 years ago.
Eclipse gives the wrong result when trying to calculate the sum of two floats.
In my code, there are 2 float variables: float from = 0.025 and float to = 1.
Then result has double variable: double value = 7 * from / to.
Eclipse compiler shows: value = 0.174999997019767760
In excel calculator, this result was value = 0.175
How can I solve this an issue?
This is simply due to your Java program not rounding the result the same way the excel calculator does. This is a result of the way computers handle floating point arithmetic. You have two options: round the result, or use the java BigDecimal class. If you want to round the result, you can use:
float from = 0.025f;
float to = 1;
double value = 7 * from / to;
DecimalFormat ds = new DecimalFormat("#.###");
double rounded = Double.parseDouble(ds.format(value));
System.out.println(rounded);
If you would rather not have to round, you can use the BigDecimal class.
Java BigDecimal
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:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I'm beginner in android developing. How can I make a double datatype i.e 56.32534 into 56.33? But I want to take it in a double variable. I know a way but it takes in String.
Double value = 56.32534;
DecimalFormat df = new DecimalFormat("0.##");
String newvalue = df.format(value);
Here, newvalueis a string. But I want to take it in a double datatype.
I need to use it's numeric value not just in display purpose only.
You can use Math.round():
double value = 56.32534;
double rounded = Math.round(100 * value) / 100.0;
The multiplication and then division by 100 is necessary because Math.round() rounds to the nearest long value.
If you want to generalize this to a variable number of digits, you can use something like this:
public double round(double value, int digits) {
double scale = Math.pow(10, digits);
return Math.round(value * scale) / scale;
}
This will even work if digits is not positive; it will round to the nearest integer if digits is 0, to the nearest 10 if digits is -1, to the nearest 100 if digits is -2, etc.
We need a little bit more precision on what you want to do. Do you want to display it that way or just use its numerical value that way ?
If it's the display your solution is ok. You could always get back the float number from the string afterwards.
On the other hand if you want to use it as a numerical value what you could do is
double rounded = (double) Math.round(myfloat * 100) /100;
I think it works. Can't test it as I'm on my mobile though
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java Integer Division, How do you produce a double?
double wang = 3 / 2;
Log.v("TEST", "Wang: " + Double.toString(wang));
Logcat output...
07-04 09:01:03.908: VERBOSE/TEST(28432): Wang: 1.0
I'm sure there's an obvious answer to this and probably I'm just tired from coding all night but this has me stumped.
In many languages, Java being one of them, the way you write a number in an expression decides what type it gets. In Java, a few of the common number types behave like this1:
// In these cases the specs are obviously redundant, since all values will be
// cast correctly anyway, but it was the easiest way to show how to get to the
// different data types :P
int i = 1;
long l = 1L;
float f = 1.0f; // I believe the f and d for float and double are optional, but
double d = 1.0d; // I wouldn't bet on what the default is if they're omitted...
Thus, when you declare 3 / 2, you're really saying (the integer 3) / (the integer 2). Java performs the division, and finds the result to be 1 (i.e. the integer 1...) since that's the result of dividing 3 and 2 as integers. Finally, the integer 1 is cast to the double 1.0d which is stored in your variable.
To work around this, you should (as many others have suggested) instead calculate the quotient of
(the double 3) / (the double 2)
or, in Java syntax,
double wang = 3.0 / 2.0;
1 Source: The Java Tutorial from Oracle
Integer division of 3 by 2 is equal to 1 with residue of 1. Casting to double gives 1.0
3 and 2 are integer constants and therefore 3 / 2 is an integer division which results in 1 which is then cast into a double. You want 3.0 / 2.0
Try: double wang = 3.0 / 2.0;
That's the expected behaviour. "3" and "2" are both int values, and when you perform 3 / 2 the result will also be an int value which gets rounded down to 1. if you cast both to double before you perform the division then you'll get the result that you expect:
double wang = (double)3 / (double)2;