java compare to from double to int tostring method - java

How do i go about using compareto for a double and i want to turn it into an int?
An example would be nice. I have been searching the java api.
also is it possible to use if and else statements with a String toString method? Mine has kept on crashing for special cases.
im a total noob to java i guess i been reading constantly to learn

If you want to compare an integer with a double you will need to convert the integer to a double. Please be aware that this won't work the other way round as an int couldn't hold all the values a double can: Values will be round down
double d = 12.3;
return (int)d;
will return 12! and doubles can hold values way bigger and small than int could
double d = 1.337E42
return (int)d;
returns 2147483647! There are many orders of magnitude in between. So please always convert the int to a double to prevent this to happen.
You can use following code for comparison:
int compare(double d, int i) {
return new Double(d).compareTo(new Double(i));
}
But keep in mind that Double differs from double as Double is an object and not a primitive type, so there will be more overhead when handling a Double compared to using a double or int.
As for the second part of your question I don't really understand what's your question/intention. Please try to clarify it.

you can try something like this
Double d = 10.0;
Integer i = 10;
d.compareTo(i.doubleValue());
or
i.compareTo(d.intValue());
I'm not sure which one you need.

You do not want to convert to String because that would compare the numbers lexicographically rather than numerically.
I will take your question to mean, "How do I create a compareTo() method for doubles?"
I also think you are using this to implement a data structure for doubles.
Here is how I would go about it.
When you construct a data structure, you will construct it as a Double object.
Double is a built-in class in java.lang package that boxes the double primitive.
Then, java will automatically cast them to that type.
The reason you want to use the Double class as the defining type for your data structure is so that you can use its built-in compareTo method. There is no way to make the primitive data type double contain the compareTo method.
Here is some code to help you get started for example:
TreeMap <Double, String> myDoubleMap = new TreeMap <Double, String> (10);
for (int i = 0; i < 10; i++)
myDoubleMap.put ( Math.sqrt( 10.0 * i) , "" + i);
System.out.println(myDoubleMap);
(Make sure you import java.util.TreeMap if you are to run this example)

I can only guess at your exact requirements. You should try to refine them a little more clearly.
If you want to compare doubles and ints, it may be tough. You have two options.
one: cast the double to an int, and compare
int compare(double d, int i) {
int dint = (int)d;
return Integer.compare(dint,i);
}
int compare(int i, double d) {
int dint = (int)d;
return Integer.compare(i,dint);
}
two: cast the int to a double, and compare
int compare(double d, int i) {
double idouble = (double)i;
return Double.compare(d,idouble);
}
int compare(int i, double d) {
double idouble = (double)i;
return Double.compare(d,idouble);
}

Related

I wont to get sum of Jtable column value (int + float) [duplicate]

The Java code is as follows:
String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense.
A double or a float datatype can hold rational numbers.
The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i will be zero.
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.
Use,
String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();
This kind of conversion is actually suprisingly unintuitive in Java
Take for example a following string : "100.00"
C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)
int i = atoi(decimalstring);
Java : mandatory passage by Double (or Float) parse, followed by a cast
int i = (int)Double.parseDouble(decimalstring);
Java sure has some oddities up it's sleeve
Using BigDecimal to get rounding:
String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();
String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();
suppose we take a integer in string.
String s="100";
int i=Integer.parseInt(s);
or
int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
use this one
int number = (int) Double.parseDouble(s);
Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.
One more solution is possible.
int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))
Example:
Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))
Output
10

In old C, what does this mean? double (*Window)(double)

I am trying to convert some old DSP code written in C into Java and later to C#. I do not understand what the argument "double (*Window)(double)" means and how to reference it in the Java code. The following function has me unsure what to do.
void WinFirI(float LowOmega, float UppOmega,
float *Shape, int Len, double (*Window)(double), float shift)
{ int i; double time,phase,shape;
// printf("WinFirI: %5.3f %5.3f %d\n",LowOmega,UppOmega,Len);
for(i=0; i<Len; i++)
{ time=i+(1.0-shift)-(float)Len/2; phase=2*M_PI*time/Len;
if(time==0) shape=UppOmega-LowOmega;
else shape=(sin(UppOmega*time)-sin(LowOmega*time))/time;
// printf("%2d %5.1f %5.2f %7.4f %7.4f\n",i,time,phase,shape,(*Window) (phase));
Shape[i]=shape*(*Window)(phase)/M_PI; }
}
So far I have written this:
public void WinFirI(float LowOmega, float UppOmega,
float[] Shape, int Len, double[] Window, float shift) {
double time;
double phase;
double shape;
// printf("WinFirI: %5.3f %5.3f %d\n",LowOmega,UppOmega,Len);
for(int i=0; i<Len; i++) {
time = i +(1.0-shift) - (float)Len/2;
phase = 2 * Math.PI * time / Len;
if(time==0) {
shape = UppOmega - LowOmega;
}
else {
shape=(Math.sin(UppOmega*time) - Math.sin(LowOmega*time)) / time;
}
// printf("%2d %5.1f %5.2f %7.4f %7.4f\n",i,time,phase,shape, (*Window)(phase));
//Shape[i]=shape*(*Window)(phase)/M_PI;
Shape[i] = shape * Window[phase]/Math.PI;
}
}
Pointer to function with parameter double returning double.
As an added note, implementing this function pointer behavior in Java would be done through an anonymous class/interface.
double Window(double param);
In Java would be:
interface WindowFnWrapper {
double Window(double param);
}
Then the function signature would be:
public void WinFirI(float LowOmega, float UppOmega,
float[] Shape, int Len, WindowFnWrapper WindowWrapper, float shift)
Every time you call Window() you would replace it with WindowWrapper.Window().
The declaration double (*Window)(double) declares a parameter Window, whose value is a pointer to a function. That function must be one which takes a single double as an argument, and returns a double.
In your C code, (well, actually the commented-out part), that pointer gets dereferenced, and the function called, passing phase as its argument. That is, the value of the expression (*Window) (phase) is just the result of calling the function whose address you passed in.
If you're using Java 8 or above, the nearest available equivalent is the Function generic class, from the java.util.function package. So if you write
import java.util.function.Function;
then you can declare the parameter as
Function<Double,Double> window
and use it as
window.apply(phase);
The only real difference between this and your C code is that the type parameters to Java generics can't be primitive types such as double.
Double is a reference type that works a bit like double, except that a Double can be null, whereas a double can't. In effect, this should make no difference to your code, except that you may want to add some error handling to deal with the case where window.apply(phase) evaluates to null.

i have encountered an error while using the pow method of java.lang.math

public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
double a=sc.nextInt();
double b=sc.nextInt();
double n=sc.nextInt();
double result=0;
for(int j=0;j<n;j++)
{
double power;
double m;
power = Math.pow(double m, double n);
double result = result+power*b;
System.out.println(result);
}
}
the compiler says .class is required in the statement " power = Math.pow(double m, double n);"
what did i miss in that statement...thank you
You don't specify the types of the arguments when you call a method.
Change
power = Math.pow(double m, double n);
to
power = Math.pow(m, n);
You should, however, give an initial value to m, or the code won't pass compilation.
There are different errors or mistakes in your code. I will go through them from top to bottom.
Your variable a is never used. You could delete the whole double a=sc.nextInt(); line without affecting your program
Your variable m is not initialized and has no value when you use it the first time
When calling a method you don't specify the data types. The data types will be taken from the variables you pass into that method. So there could be methods with the same name but with different data types in their parameter list. Imagine a method int sum(int a, int b) taking the parameters a and b that have to be of integer type. You can easily imagine, that there may be a situation where you don't want to sum integers but doubles. So you could look out for a method double sum (double a, double b) and you could use this method just like the first one but this time for variables/literals of double type. Like I wrote you don't write the data types of the parameters you pass into a method because they are determined automatically. So your Math.pow(..) call has to look like power = Math.pow(m, n);
Your code is lacking two } at the end (for the main method and for the class)
Try to use self-describing names for your variables. A counter named i may be ok but you could easily rename m to base and n to exponent and your program would automatically be easier to read.

problem with integers

can anybody look at this code and tell me why the exception happens?
public static void main(String[] args)
{
int total =100;
int discount_Ammount = 20 ;
int newAccount=Integer.parseInt( String.valueOf(Math.floor(total - discount_Ammount)).trim());
}
Method floor returns double value , then I make casting to integer, so I cast it to string then to integer... please, can anybody help?
You aren't "casting" anything. trim() removes whitespace only, which will never be present in the result of String.valueOf(double).
Use a cast:
int newAccount = (int) Math.floor(total - discount_Ammount);
Java is a strongly typed programming language, not a scripting language. Implicit conversions between strings and other types are not supported.
Or, get rid of the floor() operation altogether, since you are working with an int quantity already, and floor() is meaningless:
int newAccount = total - discount_Ammount;
If you are working with money, use the BigDecimal class so that you can use the round-off rules required by your accounting system. You won't have control of that when using double.
Did you try this?
int newAccount = (int) Math.floor(total - discount_Ammount);
Or even this!
int newAccount = total - discount_Ammount;
No need to do Integer.parseInt( String.valueOf(
To cast to int, just do (int)(blah)
So int newAccount=(int)(Math.floor(total - discount_Ammount));

How to do an Integer.parseInt() for a decimal number?

The Java code is as follows:
String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense.
A double or a float datatype can hold rational numbers.
The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i will be zero.
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.
Use,
String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();
This kind of conversion is actually suprisingly unintuitive in Java
Take for example a following string : "100.00"
C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)
int i = atoi(decimalstring);
Java : mandatory passage by Double (or Float) parse, followed by a cast
int i = (int)Double.parseDouble(decimalstring);
Java sure has some oddities up it's sleeve
Using BigDecimal to get rounding:
String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();
String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();
suppose we take a integer in string.
String s="100";
int i=Integer.parseInt(s);
or
int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
use this one
int number = (int) Double.parseDouble(s);
Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.
One more solution is possible.
int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))
Example:
Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))
Output
10

Categories

Resources