Java int cast returns 0 - java

I have the following code:
int i = (int) 0.72;
System.out.println(i);
Which yields the following output:
0
I would of imagined that the variable i should have the value of 1 (since 0.72 > 0.5 => 1), why is this not the case?
(I imagine that when casting to int, it simply cuts of the decimal digits after the comma, not taking into account of rounding up; so I'll probably have to take care of that myself?)

Correct, casting to an int will just truncate the number. You can do something like this to get the result you are after:
int i = (int)Math.round(0.72);
System.out.println(i);
This will print 1 for 0.72 and 0 for 0.28 for example.

Because when you cast a double to int, decimal part is truncated
UPDATE Math.round will give your desired output instead of Math.ceil:
System.out.println(Math.round(0.72));
// will output 1
System.out.println(Math.round(0.20));
// will output 0
You can use Math.ceil :
System.out.println(Math.ceil(0.72));
// will output 1
System.out.println(Math.ceil(0.20));
// will output 1

Casting to an int implicity drops the decimal part. That's why you get 0 because anything after the 0 is removed (in your case the 72). If you want to round then look at Math.round(...)

Explicit cast does a conversion a float/double value to an int variable (which discards the fractional part)

Java does not round-off the number like we do.It simply truncates the decimal part.
If you want to round-off the number use java.lang.Math

Casting double to int truncates the non-integer portion of the number.
To round numbers as you describe, use Math.round()

As a complete Java beginner, and just in case my experience is useful to someone, I was just making the following mistake:
int x = (int) Math.random() * 10;
... which will always set x to 0. Instead, I should've done int x = (int) (Math.random() * 10);.
Not much of a Java-know-how specific mistake, but I'll just throw this in case anyone puzzled by this stumbles upon this question.

Related

How to round a small negative double to not cause minus zero in Java [duplicate]

This question already has answers here:
How can a primitive float value be -0.0? What does that mean?
(5 answers)
Closed 2 years ago.
I need to round a small negative number to return 0.0. However, the value I'm getting is minus zero. The following code demonstrates the problem:
double value = -0.000000001;
double roundedValue = Double.valueOf(String.format(Locale.US, "%.4f", value));
System.out.println(roundedValue); // I need the roundedValue to be equal 0.0 (not -0.0)
There is a way to fix this?
You can explicitly handle the negative zero case:
roundedValue = (roundedValue == 0.0 && 1 / roundedValue < 0) ? 0 : roundedValue;
(1 / roundedValue < 0 to check for negative zero, from this answer)
Nit: use Double.parseInt rather than valueOf, to avoid the unnecessary boxing and immediate unboxing.
First, you have to realize that double values are semantically different from integers. They are imprecise, so there is always ever-so-slight error in every double value. The error, however, is small, but in unfortunate case it could be on the other side of zero - technically correct, but not what you want. This understanding is essential; if you need digit-exact arithmetic, you shouldn't be using doubles anyway, but integers/longs. Part of IEEE specification for double values also defines "negative zero", "NaN", "infinity" and so on, so technically the software is correct, but you are not using it the right way for what you want to achieve.
Second, like other people already mentioned, never use string formatting for rounding. If you need 4 decimal places, a much better way is to multiply the number by 10000, take floor/round of it and divide it by 10000 again. However, due to the facts mentioned above, you might again get some small decimal off (such as the 15th decimal digit).
On the other hand, if you just want to get rid of "rounding noise" which is sufficiently close to zero, you can also use this approach which is very robust:
if (Math.abs(x) < 0.000001d) x = 0d;
Much convenient would be:
double roundedValue = value < 0 ? (Math.ceil(value) == -0 ? 0 : Math.ceil(value)) : value;
In this case, you are going to preserve - values: for example -1.5 the result would be -1, but -0.00000001 is 0.0.

Division value casted to double with tricks in parentheses

The following code with presence and absence of parentheses produce different output. Why?
System.out.println((double) 3/6); // output 0.5
System.out.println((double) (3/6)); // output 0.0
Because in the first example you are actually doing ((double) 3)/6, and therefore the result is a double too.
In the second one, you are performing an integer division, and then you are casting the result. 3/6 = 0, and (double) 0 = 0.0.
In the first example, you are casting 3 to a double before dividing by an int. According the Java type conversion rules, the output is a double(0.5 in this case).
In the second example, you are dividing an int by an int. Since the number you are dividing is smaller than the number you are dividing with, the answer is zero. Then you are simply casting int 0 to double 0.

difference in Math.cbrt() and Math.pow()

Why does Math.cbrt(a) give a different result than Math.pow(a, (1/3))?
public class HelloWorld{
public static void main(String []args){
int a=8;
System.out.println(Math.cbrt(a));
System.out.println(Math.pow(a,(1/3)));
}
}
soln
2.0
1.0
why is there a discrepancy? Is my math wrong or syntax wrong or something that gotta do with pow?
System.out.println(Math.pow(a,(1.0/3.0)));
1/3 will be 0 thanks to integer arithmetic, so you either need to cast to a double, or simply use doubles as shown above, to get the desired result.
In Java 1/3 = 0, because you divide integer by integer. If you would use 1/3.0 your result in Math.pow would be fine.
The expression 1/3 is evaluated as an integer division, resulting in 0. Then, pow is called as pow(8, 0), which correctly returns 1. Try writing pow(a, (1.0 / 3.0)) instead.
One more thing you may take note of is, using cbrt() gives you the exact correct value for the expression whereas using pow() gives you an approximate value to it . You may ever try it by using a= 64, 125 , 216 or 343 for reference. This won't give you an exact round up value for pow() statement and in most case wrong value if you try to print the int value for the same by type-casting.
I hope this answer helps for better clarification.

Android/Java: Rounding up a number to get no decimal

How to round up a decimal number to a whole number.
3.50 => 4
4.5 => 5
3.4 => 3
How do you do this in Java? Thanks!
With the standard rounding function? Math.round()
There's also Math.floor() and Math.ceil(), depending on what you need.
You can use
int i = Math.round(f);
long l = Math.round(d);
where f and d are of type float and double, respectively.
And if you're working with only positive numbers, you can also use int i = (int)(d + 0.5).
EDIT: if you want to round negative numbers up (towards positive infinity, such that -5.4 becomes -5, for example), you can use this as well. If you want to round to the higher magnitude (rounding -5.4 to -6), you would be well advised to use some other function put forth by another answer.
Java provides a few functions in the Math class to do this. For your case, try Math.ceil(4.5) which will return 5.
new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;
Or
Int i = (int)(202.22d);
Using Math.max you can do it like this:
(int) Math.max(1, (long) Math.ceil((double) (34) / 25)
This would give you 2

How To Solve Mathematical Expression In Java?

I am trying to get percentage but the result is error, i have expression as:
Uper=(Upcount/total)*100;
where Uper is float while Upcount and total is integer i am getting the result Uper=0.
An int divided by an int will result in an int. That could be 0. Multiply 0 * 100, convert to float, and the result is still 0.0. You need at least one of the operands to be floating point before the division will give a floating point result.
Try:
Uper = ((float)Upcount/(float)total)*100.0;
The extra (float) is me being paranoid that this line might be modified in the future without fully understanding the floating-point requirement. The 100.0 is to be explicit about what you want -- a floating point result.
Perhaps changing Upcount or total to float would make more sense.
the division of 2 integers will always result in an integer which is 0 in your case.
To solve this, use the following code:
Uper = ((Double) Upcount) / total * 100
Casting at least 1 member to Double or Float will get the result you want

Categories

Resources