I'm making a simple calculator (I'm a beginner), and I was wondering why when I divide 1 by 4, I get 0. I know it has something to do with the type of number. Here is my code:
private static void calc(int a, int b,String op){
if (op.equals("add")){
double ans = a+b;
System.out.println(ans);
}
if(op.equals("subtract")){
double ans=a-b;
System.out.println(ans);
}
if(op.equals("multiply")){
double ans=a*b;
System.out.println(ans);
}
if(op.equals("divide")){
double ans=a/b;
System.out.println(ans);
}
}
I can't get my variable (ans) to have more than one decimal spot. And when the answer requires one (like 1/4), it just returns 0.
Help please.
You need to divide on a double since all your result values in double.
private static void calc(int a, double b,String op){
}
Or simply :
if(op.equals("divide")){
double ans=(double)a/b;
System.out.println(ans);
}
Although the other comments and answers are correct, they do not give enough detail (IMO).
Although ans is a double, the value of the right side of the equation is still an int.
double ans = a / b;
// equiv to:
// double ans = (double)(a / b);
So when you evaluate this you get:
double ans = (double)(1/4);
= (double)(0);
= 0.0d;
To get around this, you will need to cast one or both of the operands to a double.
double ans = ( (double) a ) / ( (double) b );
= ( (double) 1 ) / ( (double) 4 );
= 1.0d / 4.0d;
~= 0.25d;
Also note with regards to #Salah's answer that the cast from integer to double has just been moved. Since you can implicitly convert an int to a double, calling the function with an integer (such as the literal 1) will automatically convert the integer to a double. However, you may not want to allow non-integral numbers to be passed to your function, and if so, then this solution would not be correct.
Related
I am sorry for requesting help that may be basic; However, I tried every google and youtube post(at my level) and I cant seem to figure it out. Im attempting to make a method that returns me the roots of a polynomial to the 3rd power. The code works alone; however, when I attempt to put in a return function I make the return value an array (because there will be 3 roots, aka 3 values to return). When I do it I get an error beside the return function that says ["Incompatible types: double[] cannot be converted to double"]
public class RootFinder {
double[] roots = new double[3];
double R(double a, double pa, double b, double pb, double c, double pc, double d, double rp4){
/*Scanner sc = new Scanner(System.in);*/
double dx, dc, root, root1 = 0, root2;
double r1, r2, r3, remmainder, rp1, rp2, rp3;
System.out.println("Enter the quotient coefficients followed by their power:");
for(double i = -10; i<= 12; i++){
dx = 1;
dc = i;
root = (-1*dc)/dx;
r1 = a;
r2 = (root*a)+b;
r3 = (root*r2)+c;
rp1 = pa-1;
rp2 = pb-1;
rp3 = pc-1;
remmainder = (root*r3)+d;
if(remmainder == 0){
System.out.print("The Division equatates to: ");
roots[2] = ((-1*r2) + Math.sqrt((Math.pow(r2, 2)-(4*r1*r3))))/(r1*2); //quadratic formula (first root)
roots[3] = ((-1*r2) - Math.sqrt((Math.pow(r2, 2)-(4*r1*r3))))/(r1*2); //quadratic formula (second root)
//System.out.println("("+dx+"x"+dc+")"+"("+"x"+(double)root[2]+")"+"("+"x"+(double)root[3]+")");
roots[1] = (dc*-1); // factor theorem a value (first root)
break;
}
}
return roots; }
}
I thank you very much in advance for helping, I have spent 5 days trying to fix it already but I don't understand what to do to fix it. (I even attempted putting "[]" beside every double, but nothing)
Thank you,
Alejandro
You just need to use 'double[]' instead of 'double' as you want to return an array and not a single value. So, you should write something like that:
double[] R(double a, double pa, double b, double pb, double c, double pc, double d, double rp4){ ....}
And I mentioned that you tried to access values in array incorectly, in Java array indexes start from zero, so to access first value in array you have to write array[0] instead of array[1].
Your method declaration specifies a return of type double , however roots is of type double[] ie. an array of double.
There is mismatch in the return type mentioned in method declaration and what you are trying to return.
Try changing your method's declaration to this-
double[] R(double a, double pa, double b, double pb, double c, double pc, double d, double rp4) {
//Your method code here
}
How do I convert/cast a Double object to an int?
Double d = new Double(12.34);
int i = 12 //is what I'm looking for
If I had a double I would just use:
double z = 12.34;
int i = (int)z;
Note: I want it to truncate the Double (so 12.9 becomes 12) because I know that d actually was an integer that was converted to a Double.
I.e. I want to call (int) on a Double.
To perform this operation you need to call the intValue method on the Double object:
int i = d.intValue();
This method performs a cast, into an int value, on the double value wrapped within the Double object, d.
Note that it does not check for null before attempting this.
If you want to use a cast you can use
Double d = 12.34;
int i = (int) (double) d;
You can't cast from Double to int in one step.
I am going through the following code in Java:
public float a1 = 0.10f;
int Increments;
if(TotalTime > 0)
{
Increments = (int) ceil(TotalTime / Increment1);
amount = round(Increments * a1, 4);
}
Where,
TotalTime and Increment1 are integers
My questions is, Why do we need to typecast to integer just before ceil as done in the following line of code above?
Increments = (int) ceil(TotalTime / Increment1);
Because Math.ceil (I suppose it's a static import there) returns a double. As you make a restriction of the converted value (by converting to a less precise type), you need to do the conversion explicitly.
Also, please note that the argument you pass to ceil is the ratio of two integers, which is also an integer. So you're in danger of losing precision. Moreover, applying ceil to an integer is redundant, as it will return that integer itself. And the last remark: ceil expects a double as its argument. In this case, you pass an int, but the conversion is done implicitly, because it is done from a less precise to a more precise type.
The reason is that Math.ceil returns a double. You cannot implicitly cast from a double to an int. Trying to compile this:
double d = 2.1;
int i = d;
Gives you:
dur.java:4: possible loss of precision
found : double
required: int
int i = d;
^
1 error
As the error message states, the reason is that you might lose precision, so the compiler wants to be sure that you really want to allow this loss. You do this by making the cast explicit:
int i = (int)d;
Note that even so, your code won't do what you expect.
int i = 10;
int j = 3;
int k = (int)Math.ceil(i/j);
System.out.println(k); //outputs '3'
The reason is that i / j performs integer division if both i and j are integers, which rounds down. i / j is already 3, and all Math.ceil does is return 3.0, which then again gets casted to 3. You want to do floating point division instead, which is done when one or both of i and j are floating point types. You can achieve this by casting one of the integers to a double before doing the division:
int i = 10;
int j = 3;
int k = (int)Math.ceil((double)i/j);
System.out.println(k); //outputs '4'
How to convert a double value to int doing the following:
Double If x = 4.97542. Convert to int x = 4.
Double If x = 4.23544. Convert to int x = 4.
That is, the answer is always rounding down.
If you explicitly cast double to int, the decimal part will be truncated. For example:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
Moreover, you may also use Math.floor() method to round values in case you want double value in return.
If the double is a Double with capital D (a boxed primitive value):
Double d = 4.97542;
int i = (int) d.doubleValue();
// or directly:
int i2 = d.intValue();
If the double is already a primitive double, then you simply cast it:
double d = 4.97542;
int i = (int) d;
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
The double value is 420.5 and the application prints out the integer value of 420
Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean
I think I had a better output, especially for a double datatype sorting.
Though this question has been marked answered, perhaps this will help someone else;
Arrays.sort(newTag, new Comparator<String[]>() {
#Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});
Is there a Java Library function which can be used to truncate a number to an arbitrary number of decimal places?
For Example.
SomeLibrary.truncate(1.575, 2) = 1.57
Thanks
Try setScale of BigDecimal like so:
public static double round(double d, int decimalPlace) {
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
Incredible no one brought this up yet, Java API has had DecimalFormat for ages now for this exact purpose.
For most numbers, you won't be able to get an exact representation of xxx.yyyy unless you use a decimal class with guaranteed accuracy, such as BigDecimal.
There's one in commons-math. Check out http://commons.apache.org/math/apidocs/org/apache/commons/math/util/MathUtils.html:
public static double round(double x,
int scale)
It's implemented using BigDecimal, and is overloaded to allow specifying a rounding method, so you can use it to truncate, like this:
org.apache.commons.math.util.MathUtils.round(1.575, 2,
java.math.BigDecimal.ROUND_DOWN);
Update:
In the last version (Math3), this method is in the class Precision.
org.apache.commons.math3.util.Precision.round(double x, int scale, int roundingMethod)
Simply remove the fractional portion
public double trunk(double value){
return value - value % 1;
}
Use this simple function
double truncateDouble(double number, int numDigits) {
double result = number;
String arg = "" + number;
int idx = arg.indexOf('.');
if (idx!=-1) {
if (arg.length() > idx+numDigits) {
arg = arg.substring(0,idx+numDigits+1);
result = Double.parseDouble(arg);
}
}
return result ;
}
I just want to add to ubuntudroid's solution.
I tried it and it wouldn't round down, so I had to add
df.setRoundingMode(RoundingMode.FLOOR);
for it to work.
here is a short implementation which is many times faster than using BigDecimal or Math.pow
private static long TENS[] = new long[19];
static {
TENS[0] = 1;
for (int i = 1; i < TENS.length; i++) TENS[i] = 10 * TENS[i - 1];
}
public static double round(double v, int precision) {
assert precision >= 0 && precision < TENS.length;
double unscaled = v * TENS[precision];
if(unscaled < Long.MIN_VALUE || unscaled > Long.MAX_VALUE)
return v;
long unscaledLong = (long) (unscaled + (v < 0 ? -0.5 : 0.5));
return (double) unscaledLong / TENS[precision];
}
Delete the assert'ions to taste. ;)
Actually, this sort of thing is easy to write:
public static double truncate(double value, int places) {
double multiplier = Math.pow(10, places);
return Math.floor(multiplier * value) / multiplier;
}
Note that it's Math.floor, because Math.round wouldn't be truncating.
Oh, and this returns a double, because that's what most functions in the Math class return (like Math.pow and Math.floor).
Caveat: Doubles suck for accuracy. One of the BigDecimal solutions should be considered first.
To do it 100% reliably, you'd have to pass the argument as string, not as floating-point number. When given as string, the code is easy to write. The reason for this is that
double x = 1.1;
does not mean that x will actually evaluate to 1.1, only to the closest exactly representable number.
created a method to do it.
public double roundDouble(double d, int places) {
return Math.round(d * Math.pow(10, (double) places)) / Math.pow(10, (double)places);
}