Java double x 10/4=2? - java

I am new to Java and I would like to know why when you have double 10/4 you get 2? Does double always have to have decimals in order to get the right answer? Thanks.
public class Super {
public static void main(String[] args){
double x = 10/4;
System.out.println(x);
}
}

You are performing integer division before assigning the result. Integer division results in an int, the truncated result 2. To force floating point calculation and get 2.5, use double literals:
double x = 10.0 / 4.0;
or cast one to a double:
double x = (double) 10 / 4;

You are dividing with integers. You can declare those as doubles the following way (or use f for floats):
double x = 10d/4d;
System.out.println(x);

Integer division. Even though you're assigning the result to a double, you're still dividing two integers (10 and 4) so you get an integer result (floor of the actual result).
You can fix this by having one or both operands be a floating point value, for example like this:
double x = 10.0/4;
or by using type casting:
double x = (double)10/4;

Replace it by:
double x = 10.0/4.0;

Double always takes in a decimal. So it would have to be
public class Super {
public static void main(String[] args){
double x = 10.0/4.0;
System.out.println(x);
}
}

For double you need to use the following
10d/4d
Then the output is going to be 2.5 Otherwise you are just gonna end up diving two integers

The right side ofter the '=' is an integer expression, which gets converted to double only after it's calculated. So it calculates 10/4 as an integer, 2, and then converts that number to double. If you want it as a double from the beginning you have to write
double x = 10.0 / 4.0;
Only numbers that cannot be read as integer will be treated as double. Or even simpler
double x = 2.5; // :-)

Related

Decimal value issue

I've got a really annoying task to do, and stuck with it.
So: I need to write a function which gives back the value of a floating number after the decimal.
For example: the param would be:5.456-> and the returning value should be:456.
I can not use String (of course this would be easy this way).
Do you have any suggestions?
It requires some steps to do it with primitives like float or double. If you were allowed to use BigDecimal, this would just be one line of code.
Given double d = 5.456;
first, cut off the part before the floating point.
do this by int full = (int)d; which will be 5
the subtract full from it: d-full will now be only the part after the point, so .456
now use a loop to multiply the value by 10 until the "after the point" part is 0.
The special thing here is that when you use double, you have floating point precision issues. That means that d will have the value 0.4560000000000004 in between. To solve that, let's introduce an epsilon.
The full code looks like this:
private static final double EPS = 1e-5;
public static void main(String[] args) {
double d = 5.456;
System.out.println(afterDot(d));
}
private static int afterDot(double d) {
d = getDecimals(d);
while(getDecimals(d) > EPS){ //decimals will likely never be 0 because of precision, so compare with a really small EPS instead of 0
d *= 10;
}
//cast the result to an int to cut off the double precision issues
return (int)d;
}
private static double getDecimals(double d) {
int full = (int) d;
d = d-full;
return d;
}
This prints 456. I am very sure this can be optimized somehow, but it's a working first draft.
What you want is the remainder, multiplied by 10 until the remainder is 0. Using BigDecimal to prevent rounding issues that looks like this:
final BigDecimal input = new BigDecimal("5.456");
BigDecimal x = input.remainder(BigDecimal.ONE);
while (x.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) > 0) {
x = x.multiply(new BigDecimal(10));
}
System.out.println(x.longValue());
Here are two ways that don't adjust for floating point anomalies.
double s = 5.456;
System.out.println(s%1);
or
System.out.println(s-(int)s);
both print
0.4560000000000004
Or use BigDecimal and adjust the scale and subtract the integer value.
System.out.println(BigDecimal.valueOf(s)
.setScale(3)
.subtract(BigDecimal.valueOf((int)s)));
prints
.456

Division and Modulo-Division of a double value to get integer value as the result [duplicate]

I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
This being said, it does have a different behavior from Math.floor which rounds towards negative infinity (#Chris Wong)
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8) and (int)(1.2), which will both "round down" towards 0 and return 1), simply add 0.5 to the double that you will typecast to an int.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1 and y = 1):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1 and y = 2):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double is rounded up or down upon (int) typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1 whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int) typecasting, but 10.23 and 10.7 will be rounded up to 11.
(int)99.99999
It will be 99.
Casting a double to an int does not round, it'll discard the fraction part.
Math.floor(n)
where n is a double. This'll actually return a double, it seems, so make sure that you typecast it after.
This works fine int i = (int) dbl;
new Double(99.9999).intValue()
try with this, This is simple
double x= 20.22889909008;
int a = (int) x;
this will return a=20
or try with this:-
Double x = 20.22889909008;
Integer a = x.intValue();
this will return a=20
or try with this:-
double x= 20.22889909008;
System.out.println("===="+(int)x);
this will return ===20
may be these code will help you.
Try using Math.floor.
In this question:
1.Casting double to integer is very easy task.
2.But it's not rounding double value to the nearest decimal. Therefore casting can be done like this:
double d=99.99999999;
int i=(int)d;
System.out.println(i);
and it will print 99, but rounding hasn't been done.
Thus for rounding we can use,
double d=99.99999999;
System.out.println( Math.round(d));
This will print the output of 100.

Java - division of small number by big number

I have declared a variable as double. I wanted to do division of two integer and assign the output to that double variable.
But its not considering the values like 0.1 to 0.9. Only when the no is whole number like 4.0 its returning the answer
public static void main(String[] args) throws Exception
{
double itf=0;
a=4100;
b=6076
itf=a/b;
System.out.println("itf:"+itf)
}
Output is itf: 0.0
Pls help..
Most likely the variables a and b are defined as int , which will result in integer division result as 0 and when assigned to double it becomes 0.0. If you define a,b and itf as double then the result should be
0.6747860434496379
instead of
0.0
Try this code:
public static void main(String[] args) throws Exception {
double itf = 0;
double a = 4100;
double b = 6076;
itf = a / b;
System.out.println("itf:" + itf);
}
a and b are both integers, so the result of a/b is also an integer, which is then cast to a double to be stored in itf. To get the correct result, you could either define a and b as doubles, or you could cast at least one of them to double. For instance:
itf = (double)a/b;
Declare a or b as double.
OR
Cast the operation.
itf = (double)(a/b)
OR Cast one of the integers.
itf = ((double)a)/b
OR multiply with 1.0, which is double.
itf = (1.0*a)/b
The reason for your result is that you are using integer division, then assign the result to a double value. This is your code unrolled:
int a = 4100;
int b = 6076;
int temp = a / b;
double itf = temp;
If you want to explicitly use floating point division, you need to tell the compiler that you do by casting at least one (or all to be sure) member of that operation to double or float. Example:
itf = (double)a / (double)b;
Use the foloving cast to at least one operand to double
itf=((double)a)/b;
or
itf=a/((double)b);
double itf = ((double) a / (double) b);

Possible loss of precision

I am trying to run this code in java and getting following error, required int found double.
public class UseMath{
public static void main(String[]args){
int x = Math.pow (2,4);
System.out.println ("2 to the power of 4 is" + x);
}
}
If you take a look at the documentation, it says, that Math.pow() expects two doubles, and returns a double. When you pass ints to this function, it means no harm, because casting (converting) an int to double means no loss. But when you assign the value to an int, it means, it can lose precision.
Simply do this:
int x = (int)Math.pow(2,4);
or
double x = Math.pow(2,4);

Calculating remainder of two doubles in java

I have the following code :
Double x = 17.0;
Double y = 0.1;
double remainder = x.doubleValue() % y.doubleValue();
When I run this I get remainder = 0.09999999999999906
Any idea why??
I basically need to check that x is fully divisible by y. Can you suggest alternative ways to do that in java.
Thanks
Because of how floating-point numbers are represented.
If you want exact values, use BigDecimal:
BigDecimal remainder = BigDecimal.valueOf(x).remainder(BigDecimal.valueOf(y));
Another way to to that is to multiple each value by 10 (or 100, 1000), cast to int, and then use %.
You need to compare your result which allows for rounding error.
if (remainder < ERROR || remainder > 0.1 - ERROR)
Also, don't use Double when you mean to use double
Expecting precise results from double arithmetic is problematic on computers. The basic culprit is that us humans use base 10 mostly, whereas computers normally store numbers in base 2. There are conversion problems between the two.
This code will do what you want:
public static void main(String[] args) {
BigDecimal x = BigDecimal.valueOf(17.0);
BigDecimal y = BigDecimal.valueOf(0.1);
BigDecimal remainder = x.remainder(y);
System.out.println("remainder = " + remainder);
final boolean divisible = remainder.equals(BigDecimal.valueOf(0.0));
System.out.println("divisible = " + divisible);
}

Categories