Convert Double to Int

Hi,
How can I convert a double datatype eg. 0.309414484580145 to an integer?
I want to round the double to the the nearest integer. Maybe there is another way?
Regards
Pierre

    public Integer doubleToInteger(Double theDouble) {
         /* the part before the decimal */
         Integer whole = Integer.valueOf(theDouble.toString().substring(0, theDouble.toString().indexOf(".")));
         int part2 = -1;
         int part3 = -1;
         String theString = theDouble.toString();
         int length = theString.substring(theString.indexOf(".")+1).length();
         /* the parts after the decimal */
         int part1 =
          Integer.valueOf(theDouble.toString().substring(
                    theDouble.toString().indexOf(".")+1, theDouble.toString().indexOf(".")+2));
         if(length > 2) {
          part2 =
          Integer.valueOf(theDouble.toString().substring(
                    theDouble.toString().indexOf(".")+2, theDouble.toString().indexOf(".")+3));
         if(length > 3) {
         part3 =
          Integer.valueOf(theDouble.toString().substring(
                    theDouble.toString().indexOf(".")+3, theDouble.toString().indexOf(".")+4));
         /* do some rounding */
         if(part3 >= 5){
          part2++;
          if(part2 == 0) {
              part1++;
         if(part2 >= 5) {
          part1++;
          if(part1 == 0) {
              whole++;
         if(part1 >= 5) {
          whole++;
         return whole;     
    }So how unnecessary was this exactly?

Similar Messages

  • Converting double to String

    I am looking for a way to convert double to String.
    I think that I have to use wrapper like Double class and use toString(double d), but I am not sure how to do it.
    Since toString() is static method, I do not have to have an instance of the Double class, so I was wondering what's the correct way to do it.
    I need something like this:
    String MyString = new String (String1.concat ( My_doubleNumber.Double.toString() ) );
    Any Suggestions?
    Thanks!!!

    WOW thanks a lot. These are definately better than what I thought of doing originally.
    In case I need to use the wrapper class somewhere else, I am just wondering what would be a proper use of Double and String?

  • Converting Double to String without exponent

    Hi all,
    I am reading some values from Excelsheet using apache POI library. I have large numbers that need to stored into database as string and not numbers. hence, while reading the excelsheet values, i convert these number.. and the are received as double. While converting double into string I noticed that some values are represented in exponential form.. I would like to avoid this and have pure number values in the form of string,,..
    Can anybody tell me how to do it?
    Thanks in advance,
    Abdel Olakara

    java.text.DecimalFormat

  • Convert Double To String

    Hello,
    I have the following method:
    private String doubleToString(double value, int kommas)
         int stringLength;
         String mString ="";
         String mSubstringSuf ="";
         Double dValue = new Double(value);
         mString = new String(dValue.toString());
         stringLength = mString.length();
         mSubstringSuf = mString.substring(2, stringLength + 2 - kommas);
         return "0." + mSubstringSuf;
    Now I call this Method with
    value = 4.98
    kommas = 2
    I receive back the value 4.88????
    What is wrong?
    Thank you
    Werner

    That code cannot possibly return "4.88". It always returns something that begins with "0." So perhaps you are debugging the wrong code.

  • How to convert varchar to int in MSSQL?

    Hi,
    I am using mssql. how can i convert varchar to int type.
    for eg.
    id (int) txt(varchar)
    1 ---------10
    2 ---------10a
    3 ---------10b
    i want to convert varchar to int. HOw? pls explain with query.
    Thanks
    edward

    "10a" wouldn't normally be considered a number. So what sort of number do you expect it to be?
    Other than that you can look at the substring and convert/cast functions.

  • How to convert String to int in JSP?

    Hi,
    I set a session attribute in Servlet and want use it in JSP, How can I convert it to int or Integer?
    the line in my code doesn't work:
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    Thanks in advance.
    Wolf
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    <HTML>
    <HEAD>
    <TITLE>Using the for Statement</TITLE>
    </HEAD>
    <BODY>
    <H1>Using the for Statement</H1>
    <%=session.getAttribute("vehiclequantity") %>;
    <%
    int loopIndex;
    int quantity=(int)session.getAttribute("vehiclequantity") ;
    out.println(quantity);
    for (loopIndex = 1; loopIndex <=2; loopIndex++) {
    out.println("This is iteration number "
    + loopIndex + "<BR>");
    %>
    </BODY>
    </HTML>

    Learning how to read errors and understand them will help you solve your problems quicker by yourself... So lets take a look at the error and classes involved...
    The error says:
    "Cannor Resolve Symbol: method valueOf(java.lang.Object) in the class java.lang.Integer" and gives you line line where the error occurs: Integer quantity = Integer.valueOf(session.getAttribute("vehiclequantity"));
    Now, if we look at the API for the Integer we notice that are are only two valueOf methods: valueOf(java.lang.String s) and valueOf(java.lang.String s, int radix). Not valueOf(java.lang.Object) method.
    Now we look at the getAttribute(java.lang.String name) method of HttpSession we see that the method returns a java.lang.Object. Now, you know you put a java.lang.String into that attribute, but the get method returns an Object. This is because you could have put any object in there, an Integer, a String, or some other class instance. But you know it is a String, so you can cast the returned value to a String, so that you will be calling the valueOf(java.lang.String s) method of Integer with the Object returned from the HtttpSession's getAttribute(java.lang.String name) method:
    Integer quantity = Integer.valueOf((String)session.getAttribute("vehiclequantity"));

  • FM to convert double byte chars

    Hi All,
    Is there anyone know what are the function module to convert double-byte chars? Thanks.

    Seems like Blue Sky is not clear
    You want to convert what into what?
    Whats the purpose of this requirement, kindly give more details.
    Regards
    Karthik D

  • Converting from unsigned int / short to byte[]

    Can anybody help me, I am trying to convert from:
    - unsigned int to byte[]
    - unsigned short to byte[]
    I will appreciate your help lots. thanks.

    @Op.
    This code converts an integer to a byte[], but you have to consider the byte order:
            int value = 0x12345678;
            byte[] result = new byte[4];
            for (int i=3; i>=0; i--) {
                result[i] = (byte)(value & 0xff);
                value = value >> 8;
            }This is another option:
            int dummy = 7;
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            os.write(dummy);
            byte[] bytes = os.toByteArray();Kaj

  • Sorting array double or int value and keeping the associated identifier.

    Hi,
    How would I sort an array which contains a double or int value (I know how to do that) but I also want to keep the unique identifier which is associated to array element after the array has been sorted:
    example:
    identifier: 15STH7425042735
    double: 742500.000
    Thanks,
    John J. Mitchell

    Please define an it in form of entity first and then think of operating on structured data.
    a better approach here would be please create an instances of appropriate structured data arrange them in form of a list and then apply specified logic on them
    here is an example which you might think of implementing it and would more appropriate as per your stated requirements.
    public class SampleBean implements Serializable{
       private String uniqueIdentifier = new String();
       private double appValue = 0.0;
       public void setUniqueIdentifier(String uniqueIdentifier){
           this.uniqueIdentifier = uniqueIdentifier;
       public String getUniqueIdentifier(){
          return this.uniqueIdentifier;
       public void setAppValue(double appValue){
              this.appValue = appValue;
       public double getAppValue(){
            return this.appValue;
    }Sample Comparators:
    Comparator comparator4AppValue = new Comparator(){
          public int compare(Object obj1,Object obj2){
                  return Double.compare(((SampleBean)obj1).getAppValue(),((SampleBean)obj2).getAppValue());
    Comparator comparator4UniqueIdentifier = new Comparator(){
          public int compare(Object obj1,Object obj2){
                  return ((SampleBean)obj1).getUniqueIdentifier().compareTo( ((SampleBean)obj2).getUniqueIdentifier());
    };Assuming that you have acquired an Array or List 'N' Elements of SampleBean with appropriate values.
    the belows is the method of how to sort specified Array/List
    In case of array
    SampleBean sb[] = this.getSampleBeansArray();
    // in order to sort using double value inside SampleBean array.
    Arrays.sort(sb,comparator4AppValue);
    // in order to sort using unique Identifier value inside SampleBean array.
    Arrays.sort(sb,comparator4UniqueIdentifier);In case of a list
    List sb = this.getSampleBeansList();
    // in order to sort using double value inside SampleBean array.
    Collections.sort(sb,comparator4AppValue);
    // in order to sort using unique Identifier value inside SampleBean array.
    Collections.sort(sb,comparator4UniqueIdentifier);Hope this might give you some idea of how to go about.:)
    REGARDS,
    RaHuL

  • Convert Double to double

    How can I convert Double to double???

    It's an extremely important skill to learn to read the API and become familiar with the tools you will use to program Java. Java has an extensive set of documentation that you can even download for your convenience. These "javadocs" are indexed and categorized so you can quickly look up any class or method. Take the time to consult this resource whenever you have a question - you'll find they typically contain very detailed descriptions and possibly some code examples.
    Java� API Specifications
    Java� 1.5 JDK Javadocs

  • Double vs int

    Hi
    can anyone tell me the different betwen double and int.?
    in the following program, why in cannot use
    "int a = box.getWidth()"
    instead of using
    "double a = box.getWidth"
    Thanks!!
    import java.awt.Rectangle;
    public class rectangle
         public static void main(String[] args)
              Rectangle box = new Rectangle(10, 20, 30, 40);
              double a = box.getWidth();
              double b = box.getHeight();
              System.out.println("the perimeter is");
              System.out.println((a + b)*2);
    }

    These are two questions and I hope that you already know the answer of the first - in the math sense it is the difference between integer and real numbers (subsets of these sets).
    As far as the second question goes - cast what the method returns to an int.
    int a = (int)box.getWidth();
    The compiler cannot do it implicitly because double is a wider type than int.
    Mike

  • Newbie Converting double to string

    I am very new to Java Programming, but I am trying to convert a double to a string
    Here is some code of what I am trying to do:
          String output = "";
          Word words[] = new Word[ 7 ];
                        Then I add the "words" to the array
          for ( int i = 0; i < words.length; i++ ) {
             output += words[ i ].toString();
                      output +="\nListed :" + Double.toString(words[ i ].listings()) + "\n";
         return output; the listings method is type double. I think I can use toString to convert a double to a string but am not sure how to go about doing it.
    Any help is very appreciated.
    Thanks.

    I am very new to Java Programming, but I am trying to
    convert a double to a string
    Here is some code of what I am trying to do:
    String output = "";
    Word words[] = new Word[ 7 ];
    Then I add the "words" to the array
    for ( int i = 0; i < words.length; i++ ) {
    output += words[ i ].toString();
    output +="\nListed :" + Double.toString(words[ i
    ].listings()) + "\n";
    return output;the listings method is type double. I think I can use
    toString to convert a double to a string but am not
    sure how to go about doing it.
    Any help is very appreciated.
    Thanks.Wrong:
    Double.toString(words[ i ].listings())
    Right:
    words[ i ].listings().toString()

  • Problem with changing double to int!

    Hi guys. I've got a major headache trying to solve this problem, and I'm hoping maybe someone abit wiser than I could help me out.
    I've added two lots of code, one where if I input 10 as the distance I get an answer of 423.529411..etc. However I want it to display this as just 423seconds. Then print on the next line 'to Travel 10 takes 0 hours, 7mins and 3 seconds. Instead it prints 0.1117etc hours and 7.0574738 minutes and 3.529etc seconds.
       public static double enterDistance()
             System.out.println("Type the travel distance: ");
             distance = UserInput.readDouble();
             if (distance < 0)
                  System.out.println("Illegal Distance Value");
                  distance = 0;
                  enterRoadType();
                  enterDistance();
             return distance;
        public static void calcTime()
             enterRoadType();
             time = enterDistance()/speed; // time in secs
             tottime = tottime + time; //total time in hours
             System.out.println("To travel " + distance + " takes " + (time*60*60) + " seconds");
              System.out.println("To travel " + distance +" takes " + time + " hours and " + (time*convert%convert) + " minutes and " + (time *convert*convert%convert) + " seconds");
              Totaltime = Totaltime + (time*convert*convert);
              Totaldistance = Totaldistance + distance;        
        }So to try and get it to do what I want, I change this line:
    time = enterDistance()/speed; // time in secsto
    time = (int)(enterDistance()/speed); // time in secsHowever then it prints that it takes 0 seconds, 0 hours, 0 mins.
    Argh I'm so lost.
    Any help is appreciated

    I see you use (time*60*60) to display your seconds,
    this means that time = enterDistance()/speed; // time in secs is actually wrong
    So my guess is that you either or using wrong units for your speed or distance.
    I think if you try time = (int)(60*60*enterDistance()/speed); you will not get 0 for your time but i would focus on why your seconds arent seconds first

  • Exception thrown trying to convert string to int

    Hey Guys,
    i imported a csv file into my app which i divide using the split() method and put into an array then I divided the array into variables;
    fruit = piece[0];
    price = piece[1];
    unit = piece[2];Now since price has to be a double i converted it into a double;
    price2 = Double.parseDouble(price);which worked grand
    but when i try to convert unit to an integer
    unit2 = Integer.parseInt(unit);i got error
    Exception in thread "main" java.lang.NumberFormatException: For input string: "3
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    so i tried removing white spaces as follows
    target = unit.replace(" ", "");which worked and displayed grand, then i tried converting to int again but the same exception was thrown, can anyone help me with this problem, thanks
    mark

    sorry for the messed up format previously.
    Like you said the unit.replaceAll(" ", ""); did not do the trick, when displayed as a string it looked like 3 was on its own but still did not convert to int. I assume line break or something existed in the csv file like you mentioned earlier as unit was the last word in the csv file.
    when i used unit.trim(); and tried to convert to integer it worked perfectly.
    thanks all for your help,
    Mark

  • Is it possible to convert jint to int ?

    I am on a C++ program and got data from a java method on to a jint (I think 32bits) variable.
    Now I want to return this jint value as the result of the function call in my C++ program. But it does not compiled.
    Anybody know how to convert jint to any valid C++ data type (like int or double) ?
    Thanks
    Mei

    But first, it's best to understand exactly why it failed to compile originally, and understand the behavior of the cast. Is jint a typedef for int, or a typedef for something else? Are int and jint at least the same size, or different sizes? If not the same size, is the cast safe?
    (On my system, jint is a typedef for long, and both long and int are 32 bits, so the int/jint conversion is safe.)
    -slj-

Maybe you are looking for

  • E70 PDF Reader : Unable to open. File type not sup...

    This morning I have bought an E70, among others due to its highscreen resolution and the possibility to run a PDF reader on it. I have now tried ...   - the pre-installed Adobe PDF Reader   - the Adobe PDF Reader supplied with the PC Suite CD-ROM   -

  • Do I have to to have iTunes to take full advantage of the iPad2

    I am looking into getting a tablet and doing a little research. I had an iPod Touch and got rid of it.  I really hated having to connect to itunes for everything.  Since then I have removed iTunes from all of my Apple Computers. Will I be able to own

  • How can I set Firefox to open a new page each time it starts

    I need to be able to start automatically a new page when Firefox start. I have my home page setup but I'd like to start a new url in a new window each time Firefox is started. Thanks

  • Af:panelHeader appearance like in af:panelBox

    Is it possible to let the header of an af:panelHeader appeare like the header of an af:panelBox component? This means that the upper corners should look rounded and the header line should have a colored ramp. I found out, if af:panelHeader components

  • How describe model data and  get select in DB throw topLink.

    Hello, I have table from code create table t_tree id int primary key, parent_id int, value varchar2(255) Alter table t_tree add constraint constr_id_parent foreign key (parent_id) references t_tree (id) I must get query select level as lv,lpad('-@-',