Double value is boxed and then immediately unboxed in Java - java

How can I avoid using all that casts in my code in order not to have my value boxed/unboxed by sonar ?
Here's my code :
Double value = (Double) input.get(0);
int integer = new Double(value).intValue();
Double dec = Math.abs(value - (new Double(integer ).doubleValue()));
I would like to avoid casting as much as I do, but I am not sure I can keep it boxed this way.
Any ideas ?
Thank you.

I'm not sure what type input.get() returns so I'll assume that the first cast is necessary. You don't need to instantiate new Double objects on every line, you can just call its methods to return the correctly-typed values you need.
Double value = (Double) input.get();
int integerPart = value.intValue();
double decimalPart = Math.abs(value - integer.doubleValue());
It looks like you're just trying to extract the integer and decimal parts of a double, in which case this code expresses the intent a bit more clearly:
Double value = (Double) input.get();
int integerPart = value.intValue();
double decimalPart = Math.abs(value - Math.floor(value));

Related

How to do casting with respect to double and int

I have two variables:
double d1 = 15.20;
int i1 = 10;
I want to divide i1 by 100 so I can get 0.1 and then I want to add in d1.
Here are the things I tried
i1 = i1/100 result is 0
i1 = (int) ((double)i1/100); result is 0
I tried a couple of more same kind of thing but either I am getting result 0 or 2.
Can anybody please show me how to do the operation with casting w.r.t double and int. I am very new in java
i1 = (int) ((double)i1/100);
Since i1 is an integer, no matter whatever the result on right hand side it converts/rounds to integer. Hence your result 0.1 converting back to 0.
Store it in a double to retain the double result.
double result = ((double)i1/100);
Or even better, convert any of the operands to double to tell that result should be a double so that you can avoid casting completely.
double result = i1/100.0;
remember that dividing ints produce an integer too...
if you want to avoid casting then it will be ok to declare the 100 as 100.0 (a literal double), that operation will promote the variable i1 into a double and the result will produce a double too... i1 / 100.0;
the rest is similar to other answers
double d1 = 15.20;
int i1 = 10;
d1 += i1 / 100.0;
System.out.println(d1);
int/int results in an int. if you mix types, then you have a dobule.
so, for example, just divide by a double. no need to complicate formula:
double result = d1 + i1/100.0;
You should read a tutorial on the different data types and how they relate to each other, plus casting in general (It can be really confusing when you are just getting started, but you'll learn it quickly ;)).
Your specific problem can be solved by changing the type of i1 to double as integers can only contain whole numbers.
So then if you do:
double d1 = 15.2;
double i1 = 10.;
// short version
d1 += i1 / 100; // a += b is short for a = a + b
System.out.println(d1); //will print "15.3"
// extensive version
i1 = i1 / 100; // assigns the value 0.1 ti i1
d1 = d1 + i1;
System.out.println(d1); //will also print "15.3"
There are loads and loads of great tutorials on this topic on the internet, consider picking a few out and start learnng. ;)
Cheers

Converting a variable from Double to Int

Lets say that I have variable tmp which is a double, and I want to convert tmp to an int, but still have the variable called tmp. How would I do this?
Thanks
You can't have the same variable as both an int and a double.
You can have this though:
double d = 0.1d;
int i = (int) d;
d = (double) i;
System.out.println(d);
Basically you first cast your double to an integer, losing the fraction. Afterwards you cast it to a double again and assign it to your d variable. You don't have to explicitly do the casting from int to double because it is a widening conversion, but it makes it more clear what happens.
The end result is that your d variable now has a value that can be precisely interpreted by an integer but on the other hand you also, well, basically threw away your fraction. Your variable did not change its type, however.
You can write this less verbosely like this:
double d = (int) 0.1d;

How to store 0.0001352?

I have a class that has a double 'sizeinMegs' variable and whenever the value is tiny, say 0.00025 megs, it simply stores 0.0 as seen in the debug watch.
How do I save it in all its decimal glory?
Here's my code:
thePdf.setFileSizeInMegaBytes((theFile.length() / 1000000)); //that's a double
double size = theFile.length(); // this returns say 12345
size = size / 1000000; this returns 0.012345
double storedValue = thePdf.getFileSizeInMegaBytes(); // this shows 0.0 in the watch window
String value;
value = fmt(size); //this shows the right value in the string
lblTest.setText("Size: " + value + " MB");
....
public static String fmt(double d)
{
if(d == (int) d)
return String.format("%d",(int)d);
else
return String.format("%s",d);
}
It's hard to tell here, because i can't see the declaration of "theFile", but if the length() method is returning a long or int value, then the very first line of your program is doing integer/long division, and thus any value < 1 becomes 0.
If that's the case here, cast the length to a double first.
THe reason the second part works is that this declaration has an implicit cast from int/long to double, and thus any subsequent calculations results in doubles.
double size = theFile.length();
Your problem is integer division. Instead of
theFile.length() / 1000000
which will always round downwards, you could write
theFile.length() / 1000000.0
which forces this to be a non-integer division.
Whenever you place / between two expressions of int type, the result will be an int too, and it will be rounded.
You should use BigDecimal instead of double, that way you won't lose precision.
Can you show code in:
thePdf.setFileSizeInMegaBytes()
and
thePdf.getFileSizeInMegaBytes()

Implicit typecasting - Int to double

I've got an excercise from university which looks like:
int a = 10;
int b = 3;
double c = a / b;
The question is: Which value is c.
Now I would say, c is 3.3. It's casted implicit to double before calculating the result.
But the correct answer to this question is according to my records 3.0.
How this can be? Does the compiler really calculate the result first as integer and then in a second step casts it to double?
Or did I understand that incorrectly?
Does the compiler really calculate the result first as integer and
then in a second step casts it to double?
Yes
Does the compiler really calculate the result first as integer and
then in a second step casts it to double?
Yes,
Runtime first calculates the RHS result and then converts the result to double. Now in your case as RHS contains int / int so the result is in int and you don't get 3.3.
So if RHS contains double / int or int / double, the type promotion occurs and RHS operands are promoted to double before calculating the result and hence you get 3.3
See what is actually happening is :
double c = (double) a / b; //double of 3 = 3.0
you have to do
double c = a/(double)b

Conversion from Long to Double in Java

Is there any way to convert a Long data type to Double or double?
For example, I need to convert 15552451L to a double data type.
You could simply do :
double d = (double)15552451L;
Or you could get double from Long object as :
Long l = new Long(15552451L);
double d = l.doubleValue();
Simple casting?
double d = (double)15552451L;
As already mentioned, you can simply cast long to double. But be careful with long to double conversion because long to double is a narrowing conversion in java.
Conversion from type double to type long requires a nontrivial translation from a 64-bit floating-point value to the 64-bit integer representation. Depending on the actual run-time value, information may be lost.
e.g. following program will print 1 not 0
long number = 499999999000000001L;
double converted = (double) number;
System.out.println( number - (long) converted);
Are you looking for the binary conversion?
double result = Double.longBitsToDouble(15552451L);
This will give you the double with the same bit pattern as the provided long.
Binary or hexadecimal literals will come in handy, here. Here are some examples.
double nan = Double.longBitsToDouble(0xfff0000000000001L);
double positiveInfinity = Double.longBitsToDouble(0x7ff0000000000000L);
double negativeInfinity = Double.longBitsToDouble(0xfff0000000000000L);
(See Double.longBitsToDouble(long))
You also can get the long back with
long bits = Double.doubleToRawLongBits(Double.NaN);
(See Double.doubleToRawLongBits(double))
Long i = 1000000;
String s = i + "";
Double d = Double.parseDouble(s);
Float f = Float.parseFloat(s);
This way we can convert Long type to Double or Float or Int without any problem because it's easy to convert string value to Double or Float or Int.
What do you mean by a long date type?
You can cast a long to a double:
double d = (double) 15552451L;
You can try something like this:
long x = somevalue;
double y = Double.longBitsToDouble(x);
I think it is good for you.
BigDecimal.valueOf([LONG_VALUE]).doubleValue()
How about this code?
:D

Categories