Converting double to integer in Java - java

In Java, I want to convert a double to an integer, I know if you do this:
double x = 1.5;
int y = (int)x;
you get y=1. If you do this:
int y = (int)Math.round(x);
You'll likely get 2. However, I am wondering: since double representations of integers sometimes look like 1.9999999998 or something, is there a possibility that casting a double created via Math.round() will still result in a truncated down number, rather than the rounded number we are looking for (i.e.: 1 instead of 2 in the code as represented) ?
(and yes, I do mean it as such: Is there any value for x, where y will show a result that is a truncated rather than a rounded representation of x?)
If so: Is there a better way to make a double into a rounded int without running the risk of truncation?
Figured something: Math.round(x) returns a long, not a double. Hence: it is impossible for Math.round() to return a number looking like 3.9999998. Therefore, int(Math.round()) will never need to truncate anything and will always work.

is there a possibility that casting a double created via Math.round() will still result in a truncated down number
No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining.
Here are the docs from Math.round(double):
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)

For the datatype Double to int, you can use the following:
Double double = 5.00;
int integer = double.intValue();

Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);
Solved my purpose.

Related

Java int cast to float cast to int does not equal original int

Using this snippet:
public static void main(String[] args){
int i = XXX;
System.out.println( (int) ( (float) i ) );
}
If int i = 1234; then the output is 1234
If int i = Integer.MAX_VALUE; then the output is equal to Integer.MAX_VALUE
However, if int i = 1234567990;, then the output is 1234567936, which is not equal to i.
And if int i = 1235567990;, then the output is 1235568000, which is also not equal to i.
How does this casting conversion math work?
This is entirely normal for floating point maths. Both int and float are 32-bit values. float only has about 7 significant digits of precision, because it uses some of the bits for scale. As you get to large values, "adjacent" float values (i.e. going from one precisely-representable value to the next one up) are more than 1 apart - so any integer between those two adjacent values can't be represented precisely as a float.
Another way of looking at this is a version of the pigeonhole principle:
Both float and int have 2^32 possible bit patterns
There's a valid mapping from every int to a float value
Every bit pattern is a valid int, so there are 2^32 possible integer values
float also contains the value 1.5 (and many other non-integers, but we only need one of them to prove the point)
Therefore at least two int values must map to the same float, which means the mapping cannot be reversible in every case
Note that if you use double, you're fine - every int can be cast to double and then cast back to int, and you'll get the original value. However, using double and long (instead of int) you get the same problem, for the same reason, but using 64 bits instead of 32.
How does this casting conversion math work?
Casting an int to a float works the same way any float operation works: Do the math (which in this case is nothing - just take the int as is), then convert it to the 'nearest representable float' - that float which is closer to the result of the calculation than any other.
Why is it 'lossy'? See the other answer.
What's the math behind which floats are representable? Wikipedia's page on IEEE754 floating point representation explains that.

- Rounding a double up & removing the numbers after a decimal point -

Could someone tell me how I can round a double & then remove the numbers after the decimal places - & then convert this number to a String please?
e.g. start with a double value 55.6666666666667 - round it up to a double value of 56.0000000000 -
or start with 55.333333333333 - round down to a double value of 55.0000000000 -
& then remove the decimal point and trailing zeros - convert to String.
Thanks.
The best way to round a value to the nearest integer is:
int x = (int)Math.round(55.6666666666667);
x will be 56. You can also use Math.ceil() and Math.floor() to round up or down respectively. Finally to make x a string use String.valueOf(). Like this:
String xString = String.valueOf(x);
If you wanted to do it all on one line:
String xString = String.valueOf(Math.round(55.6666666666667));
You can read more about the Math class here and the String class here.
Use the Math.round() function. You can cast it to an int to eliminate the decimal places, or you can use Math.floor() or Math.ceil() to round it down or up before casting.
Assuming that you don't actually want to save the rounded value, but just want to see it as a string, this should do everything you want, where x is the double:
String s = String.format("%.0f", x);

Converting a percent, to a decimal?...using for volume control

This seems BEYOND easy but I cant see to find a clear answer...
Say I have a string (volume) that has a percentage...(80, 50, etc), I want to get the number in DECIMAL format, and then use that to figure out the volume to set the phone at. I already get the maxVolume...so it's just getting the correct value that's killing me...
Integer theVolume=Integer.parseInt(volume);
double decimalNumber = theVolume/100;
int calc=(int) (maxVolume*decimalNumber);
mgr.setStreamVolume(AudioManager.STREAM_MUSIC,calc, 0);
The decimalNumber is only coming out as 0.0...no matter what number I give it...?
Try doing it like this:
double decimalNumber = theVolume / 100.0;
The .0 at the end converts it to a decimal number.
edit: And for reference, it behaves like this because Java is trying to divide two integers (when using 100) so it tries to output the result as an integer. The result is a fraction so Java rounds it down by default to the closest integer to that fraction (0 in this case) and then assigns that integer value to your double. By instead using 100.0, you are telling Java to divide the integer by a double, which is then knows it can keep the fraction result and not round down.
Parse the volume as a double
double theVolume=Double.parseDouble(volume);
double decimalNumber = theVolume/100;
int calc=(int) (maxVolume*decimalNumber);
mgr.setStreamVolume(AudioManager.STREAM_MUSIC,calc, 0);

Java math logic error

I have the following code in my project:
int percent = 2;
int count = 10;
int percentagefill = (percent/10)*count;
System.out.println(percentagefill);
Basically what is happening is that, I'm setting two variables, percent and count. I then calculate the percentage fill. For some strange reason the percentage fill is resulting in a 0, when in this case it should be 2. Any ideas why? Thanks in advance.
intdivided by int will still result in int. In this case:
(percent/10)*count
= (2/10)*10
= (0) * 10 <-- 0.2 is rounded down to 0
= 0
You can read this question for reference. Also, here's the Java spec where is says that integer division is rounded towards 0. As for the fix, as long as floating point precision does not become an issue, just use double as PaulP.R.O said.
You could divide by 10.0, or change int percent to double percent in order to force a conversion to double. Otherwise, you are getting integer division, which truncates off the decimal part.
Here is a relevant question: "Java Integer Division, How do you produce a double?"
if you really need the result to be an int, you could do the multiply before the divide to avoid the integer division giving you zero.
int percentagefill = (percent*count)/10;
Change this line:
int percentagefill = (percent/10)*count;
To:
double percentagefill = (percent/10.0)*count;
This will use floating point arithmetic (because of the 10.0 instead of 10), and store the result in a double (which has precision past the decimal point unlike an int).
As others have mentioned, you're losing precision with integer division
The solution depends on your needs: if your result needs to be an integer anyway, multiply first:
int percentagefill = (percent*count)/10;
Could be "good enough" for you (you'll get the correct answer rounded down).
If you need to be able to get fractional answers, you need to convert things to floating point types:
double percentagefill = (percent/10.0)*count;
// ^ the .0 makes this a double,
// forcing the division to be a
// floating-point operation.
It's easy to fix:
int percent = 2;
int count = 10;
double percentagefill = (percent/10.0)*count;
System.out.println(percentagefill);
Dave Newton, your answer should have been an answer. :)
The integer 2 / the integer 10 = 0.
The integer 0 * the integer 10 = 0.
You will need a float or double data type. While working with information, always be weary of chances for the interpreter to make data type assumptions and "casts". println takes an intefer and casts to a string for display is one example.
Most of my work is in php and when working with values, 0, NULL, ERROR can all be different things and can yield unexpected results. Sometimes you may need to explicitly cast a variable to a different data type to get the intended results.
This is so due to the fact that you are using the integer data type when you should be using a floating-point data type such as double. This code should result in 2.0:
double percent = 2;
double count = 10;
double percentagefill = (percent/10)*count;
System.out.println(percentagefill);

Why does Math.ceil return a double?

When I call Math.ceil(5.2) the return is the double 6.0. My natural inclination was to think that Math.ceil(double a) would return a long. From the documentation:
ceil(double a)
Returns the smallest (closest to negative infinity) double value
that is not less than the argument and is equal to a mathematical
integer.
But why return a double rather than a long when the result is an integer? I think understanding the reason behind it might help me understand Java a bit better. It also might help me figure out if I'll get myself into trouble by casting to a long, e.g. is
long b = (long)Math.ceil(a);
always what I think it should be? I fear there could be some boundary cases that are problematic.
The range of double is greater than that of long. For example:
double x = Long.MAX_VALUE;
x = x * 1000;
x = Math.ceil(x);
What would you expect the last line to do if Math.ceil returned long?
Note that at very large values (positive or negative) the numbers end up being distributed very sparsely - so the next integer greater than integer x won't be x + 1 if you see what I mean.
A double can be larger than Long.MAX_VALUE. If you call Math.ceil() on such a value you would expect to return the same value. However if it returned a long, the value would be incorrect.

Categories

Resources