Converting String into double

Hi,
I want to convert 30.10 String Value into double.
I need to get the value as 30.10 as double only.
I tried but I am getting 30.1 only.
Please suggest me.
Thanks in advance..

user13797408 wrote:
Hi,
I want to convert 30.10 String Value into double.
I need to get the value as 30.10 as double only.
I tried but I am getting 30.1 only.
Please suggest me.
Thanks in advance..Don't do it. A short read of the documentation will tell you why (and why several such methods in many similar Java classes have been deprecated).
Simply said: 30.1 has no exact representation as a double; and it's quite possible that "30.10" will yield a different value from "30.1" (but hopefully not).
As far as printing out is concerned, you should check out NumberFormat or String.format(...). You are trying to convert a number stored in binary, that you already converted from a decimal numer (30.1) back to decimal. Sound like overkill to you?
PS: Have a look at BigDecimal. I think it may do what you want.
Winston

Similar Messages

  • Convert string into XML inside BPEL

    Hello ,
    How to convert string into xml format ? And make element and define attribute inside it ??

    There are several problems with your input:
    1. Your xml is not well-formed because the attribute values should be enclosed withing double " quotes and not single ' quotes;
    2. You use a prefix (sml) for the folowing part but you dont define the namespace:
    <ids>
    <VID ID="new"/>
    <data>
    <*sml:*attr name="std">
    <sml:value></sml:value>
    </sml:attr>
    <sml:attr name="xde">
    <sml:value></sml:value>
    </sml:attr>
    </data>
    </ids>
    Complete message should be:
    <ids xmlns:sml="somenamespace">
    <VID ID="new"/>
    <data>
    <sml:attr name="std">
    <sml:value></sml:value>
    </sml:attr>
    <sml:attr name="xde">
    <sml:value></sml:value>
    </sml:attr>
    </data>
    </ids>
    3. Do you assign this expression to a variable that is based on the schema of your message you want to parse
    Regards,
    Melvin
    * TIP Answer the question as helpful or correct if it helps you , so that someone else will be knowing that this solution helped you or worked for you and also it gives points to the person who answers the question. *

  • How to convert a string into double?

    Hi. I'm having a string with 10340.8878 which is essentially a GPS latitude coordinate. I will need to break it up separately into double type 103,40 and 88.
    103 refers to the degree
    40 refers to the minutes
    88 refers to the seconds
    I will also need to perform a double conversion: the second separated double(40) divided by a factor of 60 and the third separated double(88) divided by a factor of 360.
    How can i go about doing this?
    Thanks!

    new Double(str).doubleValue();
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Double.html

  • How to convert string into date

    Hi all,
    I m new to JDeveloper
    I m taking the date as a string then passing it as a string in the method.
    I want to convert tht string into the date of format (DD-MON-YYYY) or any other format
    require yur assistance in this job.
    THANKXX in advance
    ankit

    Is this what you are looking for:
    java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("dd-MMMMM-YYYY");          
    java.util.Date date1 = null;
    try
       date1 = formatter.parse("Thu Jun 3 09:09:30 2004");
    catch(Exception e)
       e.printStackTrace();
    System.out.println("Date1 in millis : " + date1.getTime());
    System.out.println("Date1 in string : " + date1);
    java.util.Date date2 = new java.util.Date(date1.getTime());
    System.out.println("Date2 in string : " + date2);or look at http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html for more options

  • Convert String to double with two digits

    How can I format "String" type of numbers (eg. 199.0, or 199) to return a "double" type of nubmers like 199.00, or 199.00. It should have two digits.
    For example, the input is String of 199.0, how can I get "double" 199.00. Always format as two digits.
    Thanks for your help,

    Thanks for replying.
    Here is my code. For some reason, when convert the returned String back to double in main, it cut the "0".
    What's wrong with my code? How can I get that 4.60 in double type.
    Thanks again,
    ==================================================================================
    import java.text.*;
    import java.util.*;
    import java.sql.*;
    public class NumUtils
    // Convert Double to 99.99
    public static String format(String str)
    //double d = 4.6;
    double d = Double.parseDouble(str);
    NumberFormat formatter = new DecimalFormat("0.00");
    formatter.setMaximumFractionDigits(2);
    String s = formatter.format(d);
    return s;
    public static void main(String[] args)
    String myDouble = "4.6";
    String mynewdouble = format(myDouble);
    System.out.println(" --- formatDouble = " + mynewdouble);
    double my_d = Double.parseDouble(mynewdouble);
    System.out.println(" --- Double = " + my_d);

  • Converting String into SecretKey

    Hi there,,
    I'm having probs with decrypting my encrytped data.In fact I have encrypted the data on the client side and have sent the encrypted data and the key to the server database.On the server side I wanna retrieve the key and decrypt the encrypted data with the help of it but I'm finding no way to retrieve it as a key,,moreover while trying to cast the retreived string (having converted it to an Object),,I get the ClassCastException,,
    SecretKey key=(SecretKey) myRetrievedKeyObject;
    Hope somebody can help me out with this,,,sample code highly welcomed....
    thanks...

    Here's the class I'm using for encryption and decryption..
    import java.security.*;
    import java.io.*;
    import java.util.StringTokenizer;
    import javax.crypto.*;
    import sun.misc.*;
    import java.sql.*;
    public class DesEncrypter {
    Cipher ecipher;
    Cipher dcipher;
    DesEncrypter(SecretKey key) {
    try {
    ecipher = Cipher.getInstance("DES");
    dcipher = Cipher.getInstance("DES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    public String encrypt(String str) {
    try {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");
    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);
    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    public String decrypt(String str) {
    try {
    // Decode base64 to get bytes
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    // Decrypt
    byte[] utf8 = dcipher.doFinal(dec);
    // Decode using utf-8
    return new String(utf8, "UTF8");
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    hope you can guide me...

  • "converting strings into integers in a array"

    I'm really left scrating my head trying to figure this out.
    What I have right now is this
    public class NameManager
         private names[] collection; // collection of names
         private int count;
         public NameManager() // Creating an array which for now is empty
              collection = new names[1000];     
              count = 0;
              String [] collection = {"boston", "Springfield", "New Haven",
                        "New York", "Albany"};
    Its a namemanager for my road trip project which will be sort of like mapquest. What it does, or it's supposed to do is I have a array of names of cities, that represented as strings, in a array called, collection. What my proffeser wants me to do is turn the strings into integers, so in this elements in the array can be referenced .
    It's probably so easy that I'll want to kick myself when I find out how to do it , but for whatever reason , all the information have found on the internet seems to go right over
    If any body can give some idea of how to turn the string you see above into a set of intege s I would be so grateful.

    turn the string into the index in the array
    i.e.
    boston => 0
    springfield => 1
    New Haven => 2
    New York => 3
    Albany => 4I should've mention this before but I need the names to go along with the numbers.
    This is the directions from my proffesser, I know it's not the easiest to understand
    but hopefully It will give you a better idea of what I'm talking about.
    A name manager. This object turns strings into numbers. Every time a name is added to the name manager, it is checked to see if it has already been seen. If so, return the number previously assigned to the name. If not, increment the "number of known names" and return this number as well as remember the string for future reference. You can assume that there will be no more than 1000 names in the manager. Each name is a string.
    A city. A city is a simple object: the city has a name and a number (at present).
    I got most of this part done it just strings integers part that's getting me.

  • Help needed (converting string to double)

    keep getting an error someone give me a hint
    public class q1d
        public static void main(String [] args)
            String whats;
            double x;
            x = (String)whats;
            System.out.println(+x);
    }

    Then study this tutorial
    http://java.sun.com/docs/books/tutorial/
    Specifically, this part
    http://java.sun.com/docs/books/tutorial/java/data/index.html
    You need some basic knowledge. These forums are not suitable for teaching Java. The tutorial is.

  • UCCX: unable to convert string into a number

    Hi all,
    I used the Get Digit String to pull a 4 digital numbers (stored as variable sYear) from a caller, this number is obviously stored as a string. Then i used 'set iYear=sYear' to conver this string to an integer.
    I debuged the script, when I entered number of year without following #, it worked fine. If I entered number of year and followed by #, i got the message 'unable to conver string into a number'. Can someone help me with that?
    Thanks a lot.

    Hi Reena,
    The UCCX version is 10.5.1.
    I found the problem. It works after i changed input length to 5.  'The terminating key overrides the Maximum Input Length to terminate input'.
    Thanks.

  • Converting String  into a Double value

    Hi
    iam really stuck can anyone please help that what i should do
    to convert a String variable into a double value
    iam using CLDC1.1 and MIDP2.0
    please tell me how its done
    Thank in advance

    hi,
    thanx alot it really worked now i want to convert the answer of the double variable back to string can you please tell me how to do it thanx alot

  • Convert string into java.sql.Date

    Hi,
    I want to convert a date in string form into java.sql.Date to persist into the database column with Date as its datatype in Oracle. I'm trying as follows:
    import java.sql.Date;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    public class DateTest
    public static void main(String[] args)
    String strDate = "2002-07-16 14:45:01";
         System.out.println("strDate = "+strDate);
    Date aDate = null;
    try
    if(strDate != null && !strDate.trim().equals(""))
         SimpleDateFormat aSDF = new SimpleDateFormat();
         aSDF.applyPattern("yyyy-MM-dd hh:mm:ss");
         java.util.Date utilDate = aSDF.parse(strDate);
    System.out.println("utildate = "+utilDate);
         aDate = new Date(utilDate.getTime());
         aDate.setTime(utilDate.getTime());      
         System.out.println("aDate = "+aDate);
    catch (ParseException e)
    System.out.println("Unable to parse the date - "+strDate);
    catch (Exception ex)
    ex.printStackTrace();
    System.out.println("Caught Exception :"+ex.getMessage());
    It gives the output as :
    strDate = 2002-07-16 14:45:01
    utildate = Tue Jul 16 14:45:01 IST 2002
    aDate = 2002-07-16
    If I put this value into the database table, I can see only the date. Time part is missing. Is this the problem with java.sql.Date or Oracle datatype Date? Please help me asap.
    Thanks in advance.
    Regards,
    Rajapriya.R.

    If I put this value into the database table, I can
    see only the date. Time part is missing. Is this the
    problem with java.sql.Date or Oracle datatype Date?This is not a problem, this is the defined behaviour of the Date type. RTFAPI and have a look at Timestamp, while you're at it.

  • How to convert string into date datatype

    hi! there
    i've a date in string format like MM/dd/yyyy
    eg:String sDate = "01/30/2002";
    and i want to convert this string format into java date format
    same as 01/30/2002 only
    when i write like this
    SimpleDateFormat formatter = new SimpleDateFormat ("MM/dd/yyyy");
              String sDate = "1/11/2002";
              java.util.Date oDate = formatter.parse(sDate);
    i'm getting the output
    Fri Jan 11 00:00:00 GMT+05:30 2002
    i just want the out put like 01/30/2002
    plz,help me

    Hi,
    Just use back the SimpleDateFormat object you defined.
    String myDateInStr = formatter.format(oDate);
    this will format a java.util.Date object to a string representation according to the format you specified in the instantiation of SimpleDateFormat object.

  • Need to know the best practice for converting string to double

    I have a string and want to convert to double if it is a valid number, else want to keep as it is. There can be couple of ways doing it and I want to know which one is best if I have lots of strings, specially from performance point of view.
    1) Use Double.parseDouble(myString) and catching Number format exception to detect it is not a number. One of my colleague said it does not give good performance because of exception catching,
    2) Use of org.apache.commons.lang.math.NumberUtils.isNumber() and if it is true then only parse it - so don't rely on exception.
    I did some performance testing - putting it in a loop and trying out for 2 scenarios - one loop for proper numeric value string and another for non-numeric. What I found out was if strings are not proper then parseDouble() is taking long time (because of exception catching) and in that case using NumberUtils.isNumber() makes sense.
    Would like to hear expert views on this.
    Thanks
    Manisha

    If you need it as a double you must convert it to a double and catch the exception. This means that testing it first is a waste of time in the case when the test succeeds - did your colleague think of that?
    Catching the exception is possibly slower than the test. Whether this is significant depends on the relative timings of the test and catching the exception, and also on the expected error rate. If this is below about 40% I suggest your colleague is talking through his esteemed hat.
    And of course the best test by far is the conversion itself. Using any other test runs the risk of its rules being different from those applied by the conversion.
    In any case you are obliged to write the code that catches the exception. You're not obliged to write the pre-test code.
    My personal rule for efficiency is to minimize lines of code until hard evidence to the contrary proves that further improvement is required.

  • Unable to convert string into binary

    Hello,
    I have a web application that does the following:
    1. Takes in user information via form. This includes images.
    2. Displays all the user information in a portfolio. Looks like the portfolio on this page:
    http://wrapbootstrap.com/preview/WB00PN23G
    3. When clicking on each item you are brought to a page that displays the form information and the images.
    So far it works fine but instead of sending the images as binary to SQL database I send them as strings and the problem is now when I update the code on my cloud host the images no longer display but all the text displays fine. I am thinking the problem
    is that instead of sending my images as strings I need to store them as binary and retrieve them as well. The problem is I did some research and have been unsuccessful in the ways mentioned.
    Here is my code for the form:
    //gather all the information from the form
    //I call a stored procedure to send my data to my sql database
    using (SqlCommand cmd = new SqlCommand("SaveImage", connection.con))
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = UserName.Text;
    cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = Email.Text;
    cmd.Parameters.Add("@project", SqlDbType.NVarChar).Value = Project.Text;
    cmd.Parameters.Add("@description", SqlDbType.NVarChar).Value = Description.Text;
    cmd.Parameters.Add("@img1", SqlDbType.VarBinary).Value = img1;
    cmd.Parameters.Add("@img2", SqlDbType.VarChar).Value = img2;
    cmd.Parameters.Add("@img3", SqlDbType.VarChar).Value = ppt;
    cmd.ExecuteNonQuery();
    cmd.Parameters.Clear();
    connection.con.Close();
    //Here is the stored procedure
    USE [TestDB]
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER proc [dbo].[SaveImage]
    @username varchar(100),
    @email varchar(50),
    @project nvarchar(MAX),
    @description nvarchar(MAX),
    @img1 varbinary(MAX),
    @img2 nvarchar(MAX),
    @img3 nvarchar(MAX) as
    INSERT INTO ProjectTbl(UserName, Email, ProjectName, ProjectDescription, Image1, Image2, Image3)
    VALUES (@username, @email, @project, @description, @img1, @img2,@img3)
    // Here is the code for the page that displays all the projects submitted in the form of a portfolio (just the backend not the front-end)
    public static string CreateSessionViaJavascript(string strTest)
    Page objp = new Page();
    objp.Session["controlID"] = strTest;
    return strTest;
    public static string imgString;
    //public string[] array;
    public List<string> image1 = new List<string>();
    public List<string> image2 = new List<string>();
    public List<string> image3 = new List<string>();
    public List<string> finalimages = new List<string>();
    protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
    LoadData();
    private void LoadData()
    var data = DataAccess.GetCurrentProject();
    try
    data.Columns.Add("hrefPath");
    foreach (DataRow dr in data.Rows)
    dr["hrefPath"] = "project.aspx?ID=" + dr["Id"];
    DataListProjectImg.DataSource = data;
    DataListProjectImg.DataBind();
    catch (Exception ex)
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    var imgButton = sender as ImageButton;
    if (imgButton != null)
    Response.Redirect("project.aspx?ID=" + imgButton.CommandArgument, false);
    //And here is the code for the each individual item that is clicked on in the portfolio. The images are displayed in a carousel along with the user entered data:
    protected void Page_Load(object sender, EventArgs e)
    //string code = "" + Session["Code"].ToString();
    projectId = Request.QueryString["ID"];
    if (!this.IsPostBack)
    LoadData();
    private void LoadData()
    Connection connection = new Connection();
    try
    connection.connection1();
    SqlCommand com = new SqlCommand("Select Image1,Image2,Image3,UserName,ProjectName,ProjectDescription,Email FROM ProjectTbl Where id='" + projectId + "'", connection.con);
    SqlDataReader dataReader = com.ExecuteReader();
    while (dataReader.Read())
    image1.Src = dataReader["Image1"].ToString();
    image2.Src = dataReader["Image2"].ToString();
    image3.Src = (dataReader["Image3"] != null && (dataReader["Image3"].ToString().Contains(".ppt") || dataReader["Image3"].ToString().Contains(".pptx"))) ? "assets/img/PPTdefault2.png" : dataReader["Image3"].ToString();
    hprPptLink.HRef = (dataReader["Image3"] != null && (dataReader["Image3"].ToString().Contains(".ppt") || dataReader["Image3"].ToString().Contains(".pptx"))) ? dataReader["Image3"].ToString() : "#";
    Name.Text = dataReader["UserName"].ToString();
    ProjectName.Text = dataReader["ProjectName"].ToString();
    Description.Text = dataReader["ProjectDescription"].ToString();
    Email.Text = dataReader["Email"].ToString();
    FillDataForEditProjectModal(dataReader);
    dataReader.Close();
    catch (Exception)
    throw;
    private void FillDataForEditProjectModal(SqlDataReader dataReader)
    UserName.Text = Convert.ToString(dataReader["UserName"]);
    txtEmail.Text = Convert.ToString(dataReader["Email"]);
    Project.Text = Convert.ToString(dataReader["ProjectName"]);
    txtDescription.Text = Convert.ToString(dataReader["ProjectDescription"]);
    protected void btnSaveProjDetails_Click(object sender, EventArgs e)
    SaveUploadedFiles();
    LoadData();
    private void SaveUploadedFiles()
    try
    //validation part
    if (Images1.HasFile)
    if (!CheckImageFileType(Images1))
    GenerateImageUploadJavascriptError("Image 1 Upload");
    return;
    if (Images2.HasFile)
    if (!CheckImageFileType(Images2))
    GenerateImageUploadJavascriptError("Image 2 Upload");
    return;
    if (Images3.HasFile)
    if (!Images3.PostedFile.FileName.ToLower().Contains("ppt") || !Images3.PostedFile.FileName.ToLower().Contains("pptx"))
    string script = "alert('Please Select PPT/pptx type only')";
    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "pptUploadError", script, true);
    return;
    //End validation part
    //uploading part
    string image1Path = string.Empty;
    string image2Path = string.Empty;
    string image3Path = string.Empty;
    if (Images1.HasFile)
    image1Path = Path.GetFileName(Images1.PostedFile.FileName);
    Images1.SaveAs(Server.MapPath(image1Path));
    if (Images2.HasFile)
    image2Path = Path.GetFileName(Images2.PostedFile.FileName);
    Images2.SaveAs(Server.MapPath(image2Path));
    if (Images3.HasFile)
    image3Path = Path.GetFileName(Images3.PostedFile.FileName);
    Images3.SaveAs(Server.MapPath(image2Path));
    DataAccess.UpdateProjectDetails(UserName.Text, txtEmail.Text, Project.Text, txtDescription.Text, image1Path, image2Path, image3Path, projectId);
    //end of uplaoding part
    catch (Exception ex)
    throw;
    //Server.Transfer("current.aspx");

    Hi compuluv,
    To store it in the Image object. This image object must be converted to a byte array.
    Based upon your code as below, please try to change Varchar to byte[].
    cmd.Parameters.Add("@img1", SqlDbType.VarBinary).Value = img1;
    cmd.Parameters.Add("@img2", SqlDbType.VarChar).Value = img2;
    cmd.Parameters.Add("@img3", SqlDbType.VarChar).Value = ppt;
    cmd.ExecuteNonQuery();
    For more detailed information, please check
    C# Save and Load Image from Database
    By the way, since your project is a web application, I also found a asp.net version as below.
    You can get some hints.
    http://www.dbtutorials.com/retrieve/saving-retrieving-image-cs/ 
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Converting string into inputstream and outputstream Jsch (ssh connection)

    hi,
    I'm not really sure if this is the place where i should ask this, but if it is so then tell me!
    So my problem is that everything works just fine with input output streams like in this code, but i need to change this input stream into string messadge(Which would work!!)
    The main problem is not that i can't change string to inputstream, but that when i use inputstream every commands works, and when i try to do the same with sting>inputstream this doesn't work...
    unfortunatelly newgrp server; or newgrp doesn't rerally work just frezzes :/
    anyway i solved the initial problem, because Jsch have two (probably more methods of sending info to unix server, but because there is no documentation htere no way to know :D)
    methods of sending info to server : exec and shell , the exec sends one command and only works with commands like date;ls... now the shell can easily send any type of command including newgrp server1, and everything works :)
    so we connect to the server(passw,user,host) then excecute commands, this code works perfectle but the commented code// doesn't work :
    JSch jsch=new JSch();
    String host=null;
    String user="me1234";
    host="super.server.co.uk";
    String passw="12345";
    Session session=jsch.getSession(user, host, 22);
    session.setPassword(passw);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    Channel channel=session.openChannel("shell"); //the power of shell, if i use exec doesn't excecute newgrp...
    //String command = "newgrp xxxx;"; //this doesn't work ...
    //InputStream is = new ByteArrayInputStream(command.getBytes("UTF-8"));
    //channel.setInputStream(is);
    //then somehow printout the response from server...
    channel.setInputStream(System.in); // well instead of this I'd prefer channel.send(command);
    channel.setOutputStream(System.out);
    channel.connect();
    Edited by: 842778 on 14-Mar-2011 01:42

    You seem to be leaving out the newlines.

Maybe you are looking for