How to get the int value from a floating point number? - java

If I am getting a random double, how to get only the int?
Examples:
1) 114.999 - get the "114" as an int
2) 565.343234 - get the "565" as an int.

Given the value :
float f = 114.999f;
int i = (int) f;
use a cast to downcast it to an int.

The simplest way would be to cast your double value to an int. For example,
(int) 114.9999 == 114
However, the double type can represent numbers beyond the range of an int. You may need to check if your double is below the smallest possible integer or beyond the largest possible integer to avoid integer overflow issues.

The easiest way to get the integer part of a floating point number would be a simple cast:
double d = 14.999;
int i = (int)d; //14
If you have a primitive wrapper like Double you can use the method intValue() that all subclasses of Number need to provide. However, since those are objects the references can be null and that has to be handled:
Double d = 14.999; //this makes use of auto-boxing
int i = d != null ? d.intValue() : 0; //here 0 is the default value if d is null
Note that this will just truncate the value which can lead to unexpected results due to precision issues, especially when calculations are involved. Due to that you could end up with a number like 14.999999999 when you'd expect 15 or something higher.
Another issue might be that you won't get the next smaller integer for negative values but the next higher, i.e. -14.999 will be truncated to -14.
You should keep that in mind and if those are issues for you have a look at the functions provided by the classes Math, BigDecimal etc.

Related

How to divide a figure and convert it to decimal but the remainder

I want to be able to divide 9245 by 1000 and get 9.245, and then push this number to my textview.
my code gives me 9.0 and not the remainder. Hope do I keep the remainder?
String playerScore1 = gameInfo.getGame_time() / 1000;
playerscore1.setText(Double.toString(playerScore1));
If getGame_time() method does not return a double/float, you need to explicitly add .0 to dividend, or cast it to double/float type.
gameInfo.getGame_time() / 1000.0;
Java by default performs integer division, which truncates the decimal part of result. To force floating point division you can also use suffix notation:
int/1000f
int/1000d
use 1000.0 then it'll convert it into Double, if you divide it by 1000 it will automatically cast it into an integer. and use data type Double for playerScore1 as it will return Double not String
Double playerScore1 = gameInfo.getGame_time() / 1000.0;
playerscore1.setText(Double.toString(playerScore1));
When using arithmetic operators, Java will always widen to the widest type used. One exception to this rules are arithmetic operations on types byte, char, and short, they are always converted to int. This is the reason why
byte b = 1;
b = b + 1;
will fail to compile due to type mismatches. But funnily enough
byte b = 1;
b += 1;
will compile and work as expected.
Back to topic: If you divide two ints, you get an int as result. If you divide an int and a float, you will get a float, ... Thus, the easiest way to make your expression behave as you want it to is to make one of the values either a float or a double.
You can denote a float literal by appending an f or F to a floating point number.
For double, you can:
just write a floating point number, they will default to double
add a ´.0´ to an integer literal to make it a double literal
append a d or D on a floating point number, to make it extra verbose that it is a double
Applying this to your code, one possible solution is:
double playerScore1 = gameInfo.getGame_time() / 1000.0;

Why double width = 50/110000; the output is 0.000000000000000?

This is my code :
double width = 50/110000;
System.out.println("width ori is "+width );
And the output is: 0.00000000000
What's wrong ? the expected output has to be 4.5454545454545455E-4
Any body can explain to me why?
Because you're dividing two integers, so it will only take the integer part (integer division).
Dividing integers in a computer program requires special care. Some
programming languages, treat integer division (i.e by giving the integer quotient as the answer). So the answer is an integer.
Examples :
In real life In Java
4/3 = 1.33333 4/3 = 1
25/12 = 2.083333 25/12 = 2
9/2 = 4.5 9/2 = 4
50/110000 = 0.000454545 50/110000 = 0
You can cast one of the number (or both but it's actually useless) to double to avoid that :
double width = (double)50/110000;
double width = 50d/110000;
double width = 50.0/110000;
Result of int/int returns you an integer.
So the decimal part got truncated resulting you with an integer
You need to cast:
double width = (double)50/110000;
As #Josh M has pointed, You can also try :
double width = 50d / 110000d;
Explanation to what's happening:
In Java, the default type of numbers is int, so when you write 50/110000, they're both considered int, although you defined the result to be double.
When int division occurs, the result will be 0, because they are both ints, then the double will hold this value, which will be represented as double, so you're getting 0.000000.
Possible solutions:
Coding these numbers with d: 50d/110000d.
Casting one side explicitly (the other will be implicitly cast): (double)50/110000.
50.0/110000.
See Chapter 5. Conversions and Promotions, it'll really help you.

different result in java how can it be rectified

Simple calculation gives different result in java.
int a=5363/12*5;
out.println(a);// result is 2230
But actually result should be 2234.5
How can this java result be rectified?
Two issues:
The expression 5363/12*5 gives an integer result (in particular, the division is integer).
The variable a is of type int (integer).
To fix:
double a=5363.0/12*5;
out.println(a);
Note that in general you can't expect to get exact results when using floating-point arithmetic. The following is a very good read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
5363, 12, and 5 are all being interpreted as ints. the calculation actually being performed here is:
5363/12 = 446.9… - truncated to the int value 446
446 * 5 = 2230
Try specifying a as a float, and indicate that the numbers in the calculation are also created as floats:
float a = 5363f/12f*5f
Take a as double.
Taking a as int will round it to the integer.
Because your all the literal numbers in the right hand side are integers (e.g. 5363 as opposed to 5363.0) expression is being calculated using integer arithmetic semantics i.e. / does whole number division. Thus 5262/12 equals 446 and 446*5 equals 2230. Also your variable a is an int which can only ever hold an integer value.
To fix this you need to do two things. Change the type of a to a decimal type e.g. float or double b) have at least one of 5363 and 12 represented as a decimal type e.g.
double a= 5363.0/12.0*5
Instead of using double you can re-order your expression.
Assuming 5363/12*5 = 5363*5/12 this will give you a closer answer. You have commented you want to round the result so instead you have to add half the value you are dividing by.
int a = (5363 * 5 + /* for rounding */ 6) / 12;
System.out.println(a);
prints
2235
An int is an Integer - nothing after the ..
You should be using
double a = 5363d/12*5;
It seems it has some int/double rounding issue:
double a=((double)5363/12)*5;
System.out.println("VALUE: "+a);
Prints:
VALUE: 2234.5833333333335
Edit: rounding the result to an integer value:
double a=((double)5363/12)*5;
long b=Math.round(a); //you can cast it to an int type if needed
System.out.println("ROUNDED: "+b);
Prints:
ROUNDED: 2235
Use double
double a = 5363/12*5;
System.out.println(a);
or
cast the integer, to prevent loss or precision.
int a = ((int) 5363/12*5);
System.out.println(a);

Given 35 / 4, I want an "8" returned

Rather than an "8.75" returned.
Which method? Thanks.
If I'm not completely wrong, 35/4 always evaluates to 8. Even in
double result = 35 / 4;
you will get this result (as double, i.e. 8.0). This is because 35 and 4 are both integers and therefore integer division is applied. The expression is first evaluated as integer and only the result is cast to a double value.
On the other hand, if you want the correct result 8.75 you' ll have to write
double result = 35. / 4;
in order to force floating point division to be applied. This is a common pitfall by the way.
Of course, if you have double values, like in
double a = 35;
double b = 4;
you need to either explicitely cast to an int or use Math.floor() as suggested in previous posts.
Use
Math.floor(..)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
Or, if you need to manipulate ints, not doubles, then simply assign to int:
int a = 35 / 4;
Actually, if you work with the numbers directly, or with int variables, you will get an int result automatically.
cast to int
(int)
example :
http://www.javaprogrammingforums.com/java-code-snippets-tutorials/314-how-type-cast-convert-double-integer.html
explicitly cast the expression as int
int x = 35/4
integer division causes 8 to be returned instead of 8.75
using
int myInt = (int) Math.floor(value);
8.75 will be rounded to 8. Casting to int removes decimals in case value is a double.

Error with division using double type in Java

Okay. I have been bashing my head against the wall for like 2 hours now trying to figure out why in the world double answer = 364/365; is telling me that answer is 0. Or any other combination of double for that matter, its just truncating the decimal and I just don't know why.
364/365 performs integer division (truncates the decimal).
Try double answer = 364.0/365; to force it to perform floating point division.
Something like:
double days_in_year = 365;
double answer = 364/days_in_year;
would work as well, since one of the operands isn't an integer.
You're taking an int type (364) and dividing by another int type (365) - the answer is going to be an int. This is then stored in a double type answer. You could do the following:
double answer = 364d / 365d;
More info here:
http://mindprod.com/jgloss/division.html
You need do do double division. Right now Java is interpreting it as integer division and returning the truncated int.
What you need is:
double answer = 364 / 365.0;
or
double answer = 364 / (double) 365;
The reason is that the default type of integer literals in java is int and all the result of all int based arithemetic is type casted back to int. Hence though your answer is 0.997, when it is typecasted back it becomes 0:
(int)0.997 = 0
So you can do like this:
364.0/365.0
or
((float)364)/365
All the above answers are right, would just like to add that it is all about GIGO.
double answer = 364/365;
in above code double type implies only to answer variable and arithmetic expression has both operands of int type. So the output of the arithmetic expression is also int type which is then through auto up-casting to double type gives output 0.0, just like below examples:
double ans = 4.0/0;
the above code will give output Infinity as one of the operand is Floating-point number so through auto type-casting 0 is converted to 0.0 and the result is as per the Floating-point datatype.
whereas
double ans = 4/0;
will give java.lang.ArithmeticException: / by zero exception at runtime since both the operands are of datatype int and so the output is as per the Integer datatype irrespective of ans variable datatype being double.

Categories