Hi I'm trying to run a calculation but I can't seem to put it all on one line, I have to split the result into two seperate lines to achieve the desired result (which seems a bit long winded).
Can anyone explain where I'm going wrong?
both x and y are doubles.
Example 1: (incorrect)
y=0.68
x= (Math.round(y* 10))/10;
result x=0
Example 2: (correct)
y=0.68
x= Math.round(y* 10);
x = x/10;
result x=0.7
thanks for your time.
Math.round returns variable of type long (see: Javadoc), which means that the division by 10 is performed on a long variable resulting in another long variable - that's why you lose the precision.
To make it calculate on it as on double and return double - you have to cast the result of Math.round like this:
x= ((double)Math.round(y* 10))/10;
Have you tried to explicitly specify double in your calculation:
x = ((double)Math.round( y * 10.0)) / 10.0;
Math.round returns a long....
It's hard to tell from your snippets, because they don't include variable types, but it's likely to be integer division that's killing you. When you divide two integers x and y, where x < y, you get zero:
int x = 4;
int y = 10;
int z = x/y; // this is zero.
y=0.68
x= (Math.round(y* 10)) <--- Evaluated as int since Math.round returns int /10; <-- integer division
result x=0
y=0.68
x= Math.round(y* 10) <-- x is stored as double
x = x/10; <-- double division
result x=7
I guess it's because Math.round returns either a long or an int, depending on whether y is double or float. an then you have an integer division.
in the second example x is already a double and that's why you have a double division.
When you write:
double x = (Math.round(y* 10))/10;
(Math.round(y* 10)) is a long (= 7), which you divide by 10, that gives another long (= 0). The result is then converted back to a double and stored in x.
In your second snippet:
double x = Math.round(y* 10);
This is equal to 7 and converted into a double. x / 10 is then a double operation that returns 0.7.
Related
I want to convert a double value to int when and only when 2 numbers after the dot are 0.
Example
double x = 25.001
You can use this :
double x = 25.001;
int i = (int) x;
System.out.println(x);//Input
if (x - i <= 0.01) {
x = (int) x;
}
System.out.println(x);//Output
RESULT
Input Output
25.001 25.0
25.011 25.011
If you want to use a second variable you can use :
int y = 0;
if (x - i <= 0.01) {
y = (int) x;
}
Note
But note, in case your input is not correct, you will always get 0, i like the first solution it is good then the second.
if(x-Integer.parseInt(x)>=0.001)
//Convert here
That rounded number you then cannot store in a double, as a double is always an approximation of a real value - of a series of a (negative) power of 2.
So you should go for BigDecimal as many do that want to do financial software.
If you did something like:
double adjustWhenCloseToInt(double x) {
long n = Math.round(x); // Could overflow for large doubles
if (Math.abs(x - n) < 0.01) {
x = n;
}
return x;
}
A simple
x = adjustWhenCloseToInt(x);
System.out.print(x);
Could still print 0.00000001 or such.
The solution there is
System.out.printf("%.2f", x);
Or better use a localized MessageFormat (thousand separators and such).
As floating point always bears rounding errors, I would in general go for BigDecimal, though it is a circumstantial class to use. Take care to use String constructors:
new BigDecimal("3.99");
As they then can maintain a precision of 2.
For this code block:
int num = 5;
int denom = 7;
double d = num / denom;
the value of d is 0.0. It can be forced to work by casting:
double d = ((double) num) / denom;
But is there another way to get the correct double result? I don't like casting primitives, who knows what may happen.
double num = 5;
That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:
Widening primitive conversions do not
lose information about the overall
magnitude of a numeric value.
[...]
Conversion of an int or a long value
to float, or of a long value to
double, may result in loss of
precision-that is, the result may lose
some of the least significant bits of
the value. In this case, the resulting
floating-point value will be a
correctly rounded version of the
integer value, using IEEE 754
round-to-nearest mode (§4.2.4).
5 can be expressed exactly as a double.
What's wrong with casting primitives?
If you don't want to cast for some reason, you could do
double d = num * 1.0 / denom;
I don't like casting primitives, who knows what may happen.
Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.
You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:
double d = num / (double) denom;
If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.
double d = 5 / (double) 20; //cast to double, to do floating point calculations
Note that casting the result won't do it
double d = (double)(5 / 20); //produces 0.0
Type Casting Is The Only Way
May be you will not do it explicitly but it will happen.
Now, there are several ways we can try to get precise double value (where num and denom are int type, and of-course with casting)-
with explicit casting:
double d = (double) num / denom;
double d = ((double) num) / denom;
double d = num / (double) denom;
double d = (double) num / (double) denom;
but not double d = (double) (num / denom);
with implicit casting:
double d = num * 1.0 / denom;
double d = num / 1d / denom;
double d = ( num + 0.0 ) / denom;
double d = num; d /= denom;
but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );
Now if you are asking- Which one is better? explicit? or implicit?
Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.
Also, an extra operation will definitely not make your code more efficient. Right?
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;
Note that casting the result won't do it. Because first division is done as per precedence rule.
double d = (double)(5 / 20); //produces 0.0
I do not think there is any problem with casting as such you are thinking about.
use something like:
double step = 1d / 5;
(1d is a cast to double)
Best way to do this is
int i = 3;
Double d = i * 1.0;
d is 3.0 now.
You might consider wrapping the operations. For example:
class Utils
{
public static double divide(int num, int denom) {
return ((double) num) / denom;
}
}
This allows you to look up (just once) whether the cast does exactly what you want. This method could also be subject to tests, to ensure that it continues to do what you want. It also doesn't matter what trick you use to cause the division (you could use any of the answers here), as long as it results in the correct result. Anywhere you need to divide two integers, you can now just call Utils::divide and trust that it does the right thing.
just use this.
int fxd=1;
double percent= (double)(fxd*40)/100;
Just add "D".
int i = 6;
double d = i / 2D; // This will divide bei double.
System.out.println(d); // This will print a double. = 3D
The output of below code in Java is 3.0.
Why isn't it 3.3333333...?
double a = 10 / 3;
System.out.println(a);
Because int / int returns an int (regardless of what you assign it to afterwards).
So 10 / 3 returns 3 (integer division rounds down).
This would only then get converted to double.
To fix this, make one of the values a double (so it's double / int, which returns a double):
double a = 10.0 / 3;
or
double a = (double)10 / 3;
how can i round up a floating point number to the next integer value in Java? Suppose
2.1 -->3
3.001 -->4
4.5 -->5
7.9 -->8
You should look at ceiling rounding up in java's math packages: Math.ceil
EDIT: Added the javadoc for Math.ceil. It may be worth reading all the method in Math.
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil%28double%29
public static double ceil(double a)
Returns the smallest (closest to negative infinity) double value that
is greater than or equal to the argument and is equal to a
mathematical integer. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
If the argument value is less than zero but greater than -1.0, then the result is negative zero.
Note that the value of Math.ceil(x) is exactly the value of
-Math.floor(-x).
try this
float a = 4.5f;
int d = (int) Math.ceil(a);
System.out.println(d);
I had the same issue where I was still getting the smaller int value. It was the division, not the Math.ceil. You have to add a (float) cast to the ints. This is how I fixed it:
int totalNumberOfCachedData = 201;
int DataCountMax = 200;
float ceil =(float) totalNumberOfCachedData / (float)DataCountMax;
int roundInt = (int) Math.ceil(ceil);
This will give me 2 for the value of roundInt.
See
float a=10.34f,b=45.678f;
System.out.println((int)Math.ceil(a));
System.out.println((int)Math.ceil(b));
Output
11
46
If it helps someone, here's how I get this working:
int arraySize = 3;
int pageSize = 10;
int pagesQty = (int) Math.ceil(arraySize / (float) pageSize);
System.out.println(pagesQty);
//Displays 1
Divisor must be a float in order to work properly.
I'm using this:
public static int roundDoubleToUpperInt(double d){
return (d%1==0.0f)?(int)d:(int)(d+1);
}
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.