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
Related
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.
Why java += get wrong result, and how can I prevent this problem? (for example any way show warning in IDE?)
I tried eclipse & IntelliJ but both not show any warning.
Sample code:
{
long a = 20000000000000000L;
double b = 90.0;
a += b;
System.out.println(a); // 20000000000000088 NG
}
{
long a = 10000000000000000L;
double b = 90.0;
a += b;
System.out.println(a); // 10000000000000090 OK
}
{
long a = 20000000000000000L;
double b = 90.0;
a += (long) b;
System.out.println(a); // 20000000000000090 OK
}
According to the JLS, this compound assignment expression
a += b;
is equivalent to
a = (long) (a + b);
Since b is a double, binary numeric promotion occurs before the addition happens. Both operands are converted to double values and the addition happens with floating point arithmetic.
The value 20000000000000090 cannot be represented exactly as a double and therefore you lose precision, getting 20000000000000088 instead. It then gets cast back to a long which has enough precision to represent 20000000000000088.
Your second snippet produces 10000000000000090 which can be represented exactly as a double.
Your third snippet is equivalent to
a = (long) (a + (long) b);
which uses integer arithmetic. 20000000000000090 can be represented as a long.
I don't know of any tools to warn you about this.
Related:
Is floating point math broken?
Java uses 64-bit IEEE floating point numbers, which use 53 binary digits to represent the significant. In the first example,
{
long a = 20000000000000000L;
double b = 90.0;
a += b;
System.out.println(a); // 20000000000000088 NG
}
Here the variable a is converted to a double that must use an exponent greater than 1 to represent it, and it will no longer be an exact representation of the value 20000000000000000L.
In this example, it is possible to represent a using only the significand and an exponent of 1.
{
long a = 10000000000000000L;
double b = 90.0;
a += b;
System.out.println(a); // 10000000000000090 OK
}
In this example, b is explicitly converted to a long, avoiding the need to convert a to a double and perform floating point arithmetic.
{
long a = 20000000000000000L;
double b = 90.0;
a += (long) b;
System.out.println(a); // 20000000000000090 OK
}
As not all programmer(like me) can understand binary numeric promotion、
For preventing such += coding missing, I found a simple way: just forbid all += as coding rule.
I just grep all += in my projects, and change a += b to a = a + b.
IDE shows errors while type not match while + operation, as bellow:
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;
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
I need to write a small Java program that deals with calculations involving money. Therefore it needs to have accuracy. (Eg: No float/double variables, only long).
Unfortunately, the original value I need to use is imported through a method which can only read variables as "double".
Now, I tried casting it to a long using a method similar to:
double importedValue = x;
double importedValueConverted = (long) x;
However, when I try dividing importedValueConverted by another "long" variable I get:
required: long
found: double
error: possible loss of precision
Why is that?
double importedValue = x;
double importedValueConverted = (long) x;
Note that both of these variables are declared as 'double'. This results in your error (paraphrasing): (the operation you're doing requires a) long (but when it tried it found a) double.
You want:
double importedValue = x;
long importedValueConverted = (long) x;
Forget all the casting business. If you are working with financial calculations, you can directly use BigDecimal to wrap the doubles returned by your so called method and use an appropriate rounding mechanism provided by BigDecimal that suits your needs.
Update:
This post raised an additional question which I don't think was ever answered-- why use int, or better yet, long or BigDecimal for currency calculations. This is answered here:
Why not to use double or float to represent currency (or where any exact calculations are needed)?
Because floats and doubles cannot accurately represent most base 10
real numbers.
And even when using BigDecimal, one must use the String constructor and not the float one.
This all said, your best bet is to:
Convert all values to cents and store as a long (multiply each dollar amount by 100)
Do the operations in cents
Convert back to dollars by dividing by 100 at the end
This will retain the accuracy desired. Obviously this solution has USD in mind, any conversions to foreign currencies would need appropriate consideration.
Rather than casting, consider rounding to the nearest long value:
double d = 1234.56;
long x = Math.round(d);
Tho really I ask why you'd want to go from a double to a long, as this is going to lose you the precision of the decimal values.
If you want to keep some precision (up to 3 digits, say), and you can absolutely only work with long to do so, you can multiply both doubles by 1,000, then scale all later operations by the same factor, and then scale them all back at the end, like so:
double starting = 1234.5678;
double worker = starting * 1000;
long roundedWorker = Math.round(worker);
// do other computations here...
// due to earlier scaling, adding 1000 is equivalent to adding 1 to the original
long longResult = roundedWorker + 1000;
double threeDigitPreciseResult = longResult / 1000d;
System.out.println("Adding 1 to original number as a long: " + threeDigitPreciseResult);
Update
After getting a better explanation of the problem, it sounds like what you're looking for is the functionality provided by DecimalFormat. Below is a method roundToTwoDecimals() which uses it, along with a test case demonstrating it:
import java.text.DecimalFormat;
import org.junit.Test;
public class ExampleTest {
#Test
public void test() {
double num1 = 29334.32942032432;
double num2 = 438.95940;
double result = num1 / num2;
System.out.println("Before rounding: " + result);
double rounded = roundToTwoDecimals(result);
System.out.println("After rounding: " + rounded);
}
public double roundToTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
}
Which prints out:
Before rounding: 66.82697629968585
After rounding: 66.83
You're casting x to a long than trying to assign it to a double.
That doesn't make sense.
If you want a long, you should use a long.
long longValue = (long) 4.64;
If you wanna cast double to long you do below.
double importedValue = 8.0;
long importedValueConverted = (long) 8.0;
System.out.println(importedValueConverted/(long)8);
OUTPUT: 1
double importedValue = x;
double importedValueConverted = (long) x;
you were trying to cast a double to long and reassign the casted value to a double. you should assign it to long.
Why not look at BigDecimal. It works well when I have used it. Be careful using the Double ctor though as Double is not that precise (eg it cannot accurately store 0.1). It may be more useful to use the String ctor for BigDecimal