Double into an int?

Hi,
Bit of a noob question, can anybody tell me how to parse a double into an int?
many thanks

Of course, if you want behavior other than truncation, look at the Math class.
double myDouble = 3.97;
int myInt = (int)Math.round( myDouble ); // myInt == 4
int myInt = (int)Math.floor( myDouble ); // myInt == 3
int myInt = (int)Math.ceil( myDouble ); // myInt == 4RD-R
� {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Converting a double to an int

    Can I convert a variable of type double to a variable of type int? The reason for this is I am creating a program that will draw graphs of parabolas, cubics, etc. and the user will be able to change the values for stretches, translations, etc.
    So my code for the drawing of a parabola at the moment is somewhat primitive, I just want the basic parabola drawn in. I've done a program that does exactly this using Turing (of all things...) but Java is proving to be more picky.
    int count = 0;
    int X = 0;
    double tempY = 0;
    int Y = 0;
    while(count <= 600){
         tempY = Math.pow(X - 300,2) + 200;
         Y = tempY;     //error here
         if(Y >= 0 && Y <= 400){
              g.fillOval(X, Y, 1, 1);
         count++;
         X++;
         }Don't worry about paintComponent() and all that, it's there I'm just posting the necessary parts you guys need to see.
    So the error I get is 'possible loss of precision' at the line indicated, and I know this, it's pretty obvious, but this is what I want/need to do as the fillOval will only accept ints for it's coordinates. I also tried forgetting about having the double value of tempY and doing the math to an int but then I get 'possible loss of precision' in the math line. If anyone can give me ideas/fixes to change a double into an int it would be much appreciated as this is what I really want to do, or if you can come up with alternative ways of doing what I need to do that would also be appreciated.
    EDIT
    In case you are wondering why I am adding and subtracting those values it's because my panel I'm drawing on is (600,400) and of course (0,0) is the top left corner rather than the center where it would be on a Cartesian plane, so I think I've made all the necassary adjustments so (0,0) is now in essentially the center of the panel. It's basically scanning across from the left to right and finding X^2 from '-300' to '300' but only drawing it in if the value for Y will appear in the panel. I know it's pretty fucked up and probably some really messy code, lol. I'm somewhat inexperienced and probably being a bit too adventurous.
    Edited by: vortex on Jan 15, 2008 11:07 AM
    Edited by: vortex on Jan 15, 2008 11:15 AM

    I haven't tried that, I will try that when I get to school. I think the issue could be that -300^2 may be too big to be an int? I was just thinking before I fell asleep about it last night and that could be it too...So naturally I'll just start from say, -100, or even -25 as that isn't exactly gonna fit on the graph so I'm just wasting processor power currently I suppose. Anyways I'm gonna try both of these out and get back to you guys.
    Another issue I'm foreseeing is that one of the graphs is the root of x, so I'm going to be dealing with decimals, that's fine for double but when I turn that into an int (assuming I ever figure out how to, hoping your idea, possibly coupled with mine works) how can I round/drop the decimals?
    Edited by: vortex on Jan 16, 2008 8:10 AM

  • How can I convert a String into an int?

    I need to use command-line args. So I enter "java Main 123" and I want to use 123 not as a String but as an int.
    How can I convert it into an int?
    Thank You!!
    Sprocket

    Example method (you don't need to use a method unless you do this a lot)
    private int stringTOInt (String aString)
    int result = 0;
    try
    result = Integer.parseString(aString);
    catch (Exception ex)
    System.out.println ("Failed to convert string " + aString + " to int.");
    return result;
    }

  • Java.lang.NullPointerException by parsing a string into an int

    Hi,
    I am trying to call a method with the first argument as an int.
    I have successfully tested to call it with normal int, it works.
    The problem is that the int i need to send has first to be casted from a string ( a jtext field basically)
    what i do is :
    destAddrInt = (int)Integer.parseInt(destAddr.trim());
    this.sendCommand(destAddrInt , cmdShortArray);but what ever i try it will not work, i always get the java.lang.NullPointerException.
    i have even tried to copy the value into an int:
    destAddrInt = (int)Integer.parseInt(destAddr.trim());
    int dum;
    dum = destAddrInt;
    this.sendCommand(dum, cmdShortArray);What can I do?
    Thanks for your help!

    Why do you need to typecast the int again into an integer after you have parsed it?This was actually my last try (I did several tries to find a solution)!
    Ok, know I did follow the stack trace with ex.printStackTrace(); and found that the exception was afterward (some uninitialized Set).
    And now it work, and of course even with
    Integer.parseInt(destAddr.trim())
    If I had to guess, I'd say it's in the call to the trim() method on destAddr.Trim has not be a problem).
    Thanks for your help!

  • 4 bytes into one int

    Hi, I have four bytes in my program, I'd add them together somehow so that i have a 32bit string, how can I do this?
    I tried adding them together and storing into an int but when i tried to do bit shifting I got an unexpected result.
    int x = byte[0] + byte[1] + byte[2] + byte[3];Where am i going wrong?
    thx
    Edited by: Unconditional on Jan 25, 2008 12:35 PM

    You need to use bit shifting. However, you need to decide whether [0] is the high byte or the low byte (big-endian or little-endian).
    EDIT: Also, "32bit string"? You mean "32-bit int" right?
    Edited by: paul.miner on Jan 25, 2008 2:39 PM

  • Help!!!!!  anyone know how to change a Double to an int??

    Help!!!!! anyone know how to change a Double to an int?? for use in an array[int].

    I don't know why would you want to depend on a double value to build your array but programmatically just use plain old cast: i = (int) double_value;
    Keep in mind though, the integer value will be truncated.

  • MDO Query errors in log -[Cannot fetch column 22, which has JDBC type DOUBLE, into a Java variable of type ]

    Hello,
    We are seeing a lot of log messages like the one below when an MDO select query is run. There is a message for every numeric column. There doesnt seem to be any issue with the queries working properly its just creating a lot of log messages. Has anyone else had this issue?
    Exception of type com.sap.sql.log.OpenSQLException caught:
    Cannot fetch column 22, which has JDBC type DOUBLE, into a Java variable of type
    float..
    [EXCEPTION]
    com.sap.sql.log.OpenSQLException: Cannot fetch
    column 22, which has JDBC type DOUBLE, into a Java variable of type float.
    at com.sap.sql.log.Syslog.createAndLogOpenSQLException(Syslog.java:83) ...

    Hi Christian,
    You are right. As in your case it is a select query it does not reflect the error automatically. In my case, I had an insert query so it failed then and there, which was easier to debug and fix.
    I have one question regarding your case. When you read the MDO using the query, what do you do with the output? Do you assign it to any local/transaction property in the output links of the query block or in a proceeding assignment block?
    Because, the error mentions that the assignment of float to double datatype fails. So, in theory there should be some assignment done with the output.
    Please check if you could figure out this part in your transaction.
    Regards,
    Saumya Govil

  • Creating polygons with an array of doubles instead of ints

    Hi,
    I want to create a polygon using:
    Polygon u = new Polygon(xPoints, yPoints, numTs);
    my problem is that my x & y points are stored in double arrays not ints. Is there a way to create a polygon using double arrays instead of ints?
    cheers,
    elmicko

    or cast them as int. imaginr posX, posY, width and height are doubles.
    Rectangle rect = new Rectangle( (int)posX, (int)posY, (int)width,(int)height );or, with an array of doubles:
    Rectangle rect = new Rectangle( (int)array[0], (int)array[1], (int)array[2],(int)array[3] );

  • Reading content of a file into an int array

    How do i use FileReader rd = new FileReader(filename) to read the contents into an int array?

    public static int[] parse_file(String filename)
         Vector vec = new Vector();
         int num[];
         num = new num[vec.size()];
         try {
              BufferedReader br = new BufferedReader(new FileReader(filename));
              String line;
              while((line = br.readLine()) != null) {
              vec.add(line);
              for (int i = 0; i < vec.size(); i++) {
              num[i] = (int) vec.get(i);
              System.out.println("Number=" + num);
         catch(IOException e) {
              System.out.println("error");
         return num;
    Maxsum.java:22: cannot resolve symbol
    symbol : class num
    location: class Maxsum
         num = new num[vec.size()];
    ^
    Maxsum.java:30: inconvertible types
    found : java.lang.Object
    required: int
              num[i] = (int) vec.get(i);
    How do i initialize the array?if i do not initialize it, there'll be array not initialized error also..How do i convert the String to int?

  • Converting a byte[] into an int

    I am using the MD5 hash function to create a message digest. When the hash function is complete it returns a byte[]. I want to turn this byte [] into an int, so that I can exclusive or (^) it to a node id according to this traceback algorithm I am trying to implement.
    Basically, I need to turn a byte[] into an int, and then from an int back into a byte[].
    I've looked throughout the forums at different implementations of this, but some do not return the same byte[] as the original, other's have said to use the ByteBuffer, but how do I use it to turn a byte[] into an int?
    Any help would be great, thanks!!!

    Unfortunatly that will not work. As a previousposter
    indicated, you must mask off the lower 8 bits ofeach
    byte after converting to int (or the equivilentmask
    after shifting).Um? Why would the "sign" bit be getting shifted INTO
    the lowest bit?D'oh! Sorry. My bad. When bytes[n] gets "implicitly" cast to do the calculation. Gak! Nevermind.
    Corrected would be:
    iBytesVal = ((bytes[3] & 0xFF) << 24);
    iBytesVal |= ((bytes[2] & 0xFF) << 16);
    iBytesVal |= ((bytes[1] & 0xFF) << 8);
    iBytesVal |= (bytes[0] & 0xFF);

  • Turning substring into an int

    Hello,
    I was wondering if there is any way to turn a substring into an int. Im working on a project that involves me using a number from a text document and do some arithmatic equations. I tried using the valueOf method like so: valueOf(program.get(counter).substring(6,7)); but it gives the cannot find symbol method valueOf(java.lang.String). any help is much appreciated.

    Not odd at all. And BTW, you do not need to ever import 'java.lang'. It is implied in any source file. You would have to import any other package, such as 'java.util' as you indicated in your example.
    As to why you need to type Integer.parseInt(), well, you are invoking a method. Granted, the method is on a java.lang class that is always available. However, think of it from the viewpoint of a compiler designer. He/she cannot anticipate all the type conversions you would want to perform (not should this even be a goal). Rather, there is a limited set of pre-defined conversions that take place in the Java Language Specification. The remainder are achieved via existing java library classes or your own custom code. That's life. :^)
    - Saish

  • DrawLine using double instead of int

    I'm trying to use the java.awt to draw a line but I would like to use doubles instead of ints.
    the normal way would be to use drawline(int x, int y , int x2 , int y2);
    but i cant find a way to drawline( double x, double y, double x2, double y2)
    any idea's?
    Some more detail about this is I�m trying to create a package to draw a graph and my points are in double (and I would like them to stay that way) is there a way?
    Many Thanks, John

    if you want to keep it in doubles you could use Line2D.Double from the java.awt.geom package. Then instead of a call to drawLine(int, int, int, int) call draw(line2D) passing in the line2D. As it implements the shape interface it will know what to do. Note to do this call you'll have to cast the Graphics object to a Graphics2D.
    Hope this helps
    Mike

  • Store a double into a variable of type int

    if I have a calculated value of type "double", and I would like to store it as an "int" in a variable of type "int".
    when i casted the double to int, seems it doesn't work.
    what should the command be?
    Thanks in advance!

    post your expression. I'd bet you aren't casting the value of assignment but rather a component of some computation.
    Something like this:
    double dub = 2.4;
    int returnvalue = (int)12/dub;as opposed to
    double dub=2.4;
    int returnvalue = (int)(12/dub);In the first entry, you would be casting 12 to an int and then dividing by a double and assigning the result to an int (returnvalue). Java will always try to expand precision to greatest common denominator, so the return value of the division will be a double (and hence the loss of precision assigning it to an int). The second entry properly casts the result of the whole expression as an int before assigning it to the int variable.

  • Asking for directions - Transforming int // short // double into string

    I've been searching around the forums for a tutorial to transform an int or short or long back into a string, and I can't seem to find one. Could a kind person direct me to the tutorial for making integers into strings?

    String.valueOf(...)

  • Turning double into percent values..

    let's say i have a double value like this
    0.05989773557341125
    i want to turn it into a percentage
    i tried:
    int percent = (int) number*100;
    but it doesn't work and a zero comes out of it

    int percent = (int) number*100;That casts number to an int (which rounds it down to 0) then multiplies it by 100.
    int percent = (int) (number*100.0);That does the multiplication on floating point types, then casts the result to an int, truncating the decimal part.

Maybe you are looking for