Converting StringBuffer to double

Hi all,
The only I could find converting a StringBuffer object to a double is through converting it first to a String with toString and then parsing it with parseDouble(). Is there a way to do it without doing toString() in the middle?
Thanks a bunch.
class MyStringBuffer{
public static void main(String args[]){
StringBuffer firstOperand=new StringBuffer(35);
firstOperand.append("123.");
firstOperand.append("06");
String result=firstOperand.toString();
System.out.println(Double.parseDouble(result));

Hi Mr.Matthew!
Consider some hints:
1) StringBuffer is the most efficient way to manipulate strings, none is better unless always a pair of strings (numeric representation) are to be used and few times
2) Double.parseDouble() is also efficient because it is a static method, it doesn't create a Double instance!
3) Sun implemented both classes after intensive research, so there aren't bugs to fix, they are closer to optimal solution.
I understand you are intended to maximum efficiency but sometimes it doesn't be reached at low operational cost.
Success!

Similar Messages

  • How to convert BigDecimal to double

    Error Message: {http://xmlns.oracle.com/OracleRules1/OracleRules1_DecisionService_1}operationErroredFault
    Fault ID default/BusinessRule2!1.0*b48a0c26-0b59-41e0-8939-55c7589d76f1/BusinessRule2_BPELProcess/10004-BpInv0-BpSeq2.9-4
    Fault Time Jan 15, 2010 11:52:33 AM
    Non Recoverable System Fault :
    <bpelFault><faultType> <message>0</message></faultType><operationErroredFault xmlns="http://xmlns.oracle.com/OracleRules1/OracleRules1_DecisionService_1"><part name="payload"><errorInfo xmlns="http://xmlns.oracle.com/OracleRules1/OracleRules1_DecisionService_1"><errorMessage>cannot convert from type 'java.math.BigDecimal' to type 'double' at line 5 column 9 in main</errorMessage></errorInfo></part></operationErroredFault></bpelFault

    >
    > how to convert bigdecimal to double in webdynpro java
    Hi,
    Try this:
    double x = wdContext.currentContextElement().getBigdecimalAttribute().doubleValue();
    Refer methods applicable on Bigdecimal here -
    http://code.google.com/android/reference/java/math/BigDecimal.html
    Regards,
    Anagha
    Edited by: Anagha Jawalekar on Nov 17, 2008 12:08 PM

  • SSAS 2005 Error converting numeric to double

    Hello,
       im getting error: "Errors in the back-end database access module. OLE DB was unable to convert a value to the data type requested for column 0.", "Errors in the OLAP storage engine: An error occurred while the 'Unit Price' attribute of the 'Dim Work' dimension from the 'S1_DWH' database was being processed." This error rises when OLAP tries to convert numeric(18,6) to double with value less than 1 and bigger than -1. Same problem with measures with these values. With any other values cube and dimensions works well. This error occured on production server.  On dev server works well without any errors.
    Any ideas?

    Hi,
    This issue could be caused by the data difference between dev DW and product DW. Could you check if there is unexpected null value in database? Also, if you are using named query, could you run the query on product server for test?
    Here are two similar threads:
    http://social.msdn.microsoft.com/forums/en-US/sqlanalysisservices/thread/1c06a7a6-9885-4756-a055-50b83b25029e/
    http://social.msdn.microsoft.com/Forums/en-US/sqlanalysisservices/thread/74d4a3d4-72fe-46fb-b3a0-a8bab7ac643f
    Hope this helps.
    Raymond

  • Convert StringBuffer to char*

    Hi,
    I try to convert a StringBuffer field to a char* in C++.
    But it doesn't work at all.
    I try to get the String of the StringBuffer and then convert this String with UTF.
    I post my code. If anyone can help, please ....
         jfieldID fidLoN = env->GetFieldID(cls, "pszLogicalName", "Ljava/lang/StringBuffer;");
         jobject strBuff = (jobject) env->GetObjectField(pModelInfo, fidLoN);          
         jclass jclsStrBuf = env->FindClass("Ljava/lang/StringBuffer;");
         jmethodID jmethToStr = env->GetMethodID(jclsStrBuf, "toString", "()Ljava/lang/String;");
         jstring str1 = NULL;
         env->CallObjectMethod(str, jmethToStr, str1);
         const char *buf1 = env->GetStringUTFChars(str1,0);
         strcpy(BUF1, buf1);
    // C++ structure
         modInf.pszLogicalName = (char*) BUF1;
    Thanks a lot
    Zauz

    void testmethod(char *s) {
      if(s != NULL) {
        printf("Received: %s\n", s);
        sprintf(s, "hello world");
    #ifdef __cplusplus
    extern "C" {
    #endif
    JNIEXPORT void JNICALL Java_exampleJNI_testmethod(JNIEnv *jenv, jclass jcls, jobject jarg1) {
        char *arg1 ;
        (void)jenv;
        (void)jcls;
            arg1 = NULL;
            if(jarg1 != NULL) {
                /* Get the String from the StringBuffer */
                jmethodID setLengthID;
                jclass sbufClass = (*jenv)->GetObjectClass(jenv, jarg1);
                jmethodID toStringID = (*jenv)->GetMethodID(jenv, sbufClass, "toString", "()Ljava/lang/String;");
                jstring js = (jstring) (*jenv)->CallObjectMethod(jenv, jarg1, toStringID);
                /* Convert the String to a C string */
                const char *pCharStr = (*jenv)->GetStringUTFChars(jenv, js, 0);
                /* Take a copy of the C string as the typemap is for a non const C string */
                jmethodID capacityID = (*jenv)->GetMethodID(jenv, sbufClass, "capacity", "()I");
                jint capacity = (*jenv)->CallIntMethod(jenv, jarg1, capacityID);
                arg1 = (char *) malloc(capacity+1);
                strcpy(arg1, pCharStr);
                /* Release the UTF string we obtained with GetStringUTFChars */
                (*jenv)->ReleaseStringUTFChars(jenv,  js, pCharStr);
                /* Zero the original StringBuffer, so we can replace it with the result */
                setLengthID = (*jenv)->GetMethodID(jenv, sbufClass, "setLength", "(I)V");
                (*jenv)->CallVoidMethod(jenv, jarg1, setLengthID, (jint) 0);
        testmethod(arg1);
            if(arg1 != NULL) {
                /* Append the result to the empty StringBuffer */
                jstring newString = (*jenv)->NewStringUTF(jenv, arg1);
                jclass sbufClass = (*jenv)->GetObjectClass(jenv, jarg1);
                jmethodID appendStringID = (*jenv)->GetMethodID(jenv, sbufClass, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
                (*jenv)->CallObjectMethod(jenv, jarg1, appendStringID, newString);
                /* Clean up the string object, no longer needed */
                free(arg1);
                arg1 = NULL;
    #ifdef __cplusplus
    #endifJava code:
    class exampleJNI {
      public final static native void testmethod(StringBuffer jarg1);
    public class example {
      public static void testmethod(StringBuffer SBUF) {
        exampleJNI.testmethod(SBUF);
    public class main {
      public static void main(String argv[]) {
        System.loadLibrary("example");
        StringBuffer sb = new StringBuffer(20);
        sb.append( "Java message" );
        example.testmethod(sb);
        System.out.println("returned: " + sb);
    }Run main and you should get:
    Received: Java message
    returned: hello world
    Code adapted from one of the SWIG examples.

  • Converting from a double to scientific notation

    does anyone know how I can convert a double value to scientific notation?

    java.text.DecimalFormat can do that.

  • Converting from Int/Double to Wording Format

    Hi,
    Does anyone has any sample program to convert double values into wording (this functionality is used to convert currency value) up to Trillion value.
    For eg: 1000.90 One thousand And Ninety Cents
    I have written a program which can accept up to 1 Billion. This is because that 'int' can accept bits up to that level only. I am unsure how go beyond that because when I declare the type to double, the compiler gave me the same error.
    Thank you.

    Check
    http://www.rgagnon.com/javadetails/java-0426.html
    but consider keeping locale specific texts in properties
    file and access them through resource bundles.

  • 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.

  • 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 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

  • Converting array of Double Precision values to U16 for MODBUS

    Hello,
    I am trying to send over pressure and temperature information via the Input Register array in MODBUS TCP.  My question is, how to I properly send over an array of double precision values without loosing my data?
    For example, my array of data looks like:
    12.0001
    32.001
    0.00051234
    0.0014838
    1.02
    12.0232
    31.920
    Thanks so much.

    Thank you Ravens Fan for replying.
    I missed one extra point of data.  Below is what I'd like to send:
    12.0001
    32.001
    0.00051234
    0.0014838
    1.02
    12.0232
    31.920
    2046
    The array above is an array of double precision values.  I will convert that array to an array of single precision floating data to reduce data size.
    Since I have eight pieces of single precision floating point data now, I will need to write to 16 registers correct?  What is the best method to split up each piece of data into two consecutive registers?
    Attached is a Slave Send Data.VI that I want to send this data through.  The end goal is to have a Master PC (not using labview, but a MODBUS utility) to read my MODBUS TCP message from the "Slave Send Data.vi" 
    Thanks
    Attachments:
    Slave Send Data.vi ‏15 KB

  • N95 8gb converts music at double speed

    I converted a few mp3's with the music manager and all was fine so I did a few more and for some reason all of them where converted at a higher tempo than they should be and I cant seem to find a setting to change that can anyone help please.
    All my music sounds like the sound track to alvin and the chipmunks.
    I know I could just transfer the music withought conversion but the whole point of converting is to save space.
    Message Edited by shavedape on 06-Apr-2008 12:27 PM
    http://www.passwithlee.com

    Like I said in my original post dont want to store them on the phone as mp3. So much as the help given is appreciated if I had wanted to know how to transfer mp3's I would of asked that.
    I was hoping someone had a solution for the specific problem. One that achieved what was intended, which was to convert mp3/wav/wmv etc to aac so as to reduce there size somewhat so as to aford me more usable space.
    Transfering as mp3 while still an option is not the problem nor does it solve it niether does only putting on the mp3's / cd's that I listen to as my mood changes so does the music I listen to.
    Message Edited by shavedape on 06-Apr-2008 05:21 PM
    http://www.passwithlee.com

  • 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.

  • Converting from string to double (formula)

    Hi All,
    I have a formula stored in properties file (i am doing some android dev) and retrieveing that formula using following stmt
    double c = 35.0;
    String res = this.getResources().getText(R.string.celsiusfahrenheit).toString();
    The returned value of string res is (1.8*c)+32
    How do i make the above stmt to substitue value of c into above equation and returned me the result value.
    thx
    vinod

    vinod_kmr wrote:
    Hi All,
    I have a formula stored in properties file (i am doing some android dev) and retrieveing that formula using following stmt
    double c = 35.0;
    String res = this.getResources().getText(R.string.celsiusfahrenheit).toString();
    The returned value of string res is (1.8*c)+32
    How do i make the above stmt to substitue value of c into above equation and returned me the result value.
    thx
    vinodas I understand you actually want to solve. if so, and res always returns that formula, then you can skip the properties file and just solve it already. something like:
    double result = (1.8*c) + 32.0if the result you are looking for is res with the value of the double substituted for c in the formula then the first step is to convert the the double c into a string and sticking that in res using String.replace(). something like
    res = res.replace("c", Double.toString(c));of course I don't know if String in android is like java.lang.String (same with Double) but I'm sure an equivalent exist.

  • Converting packed signed decimal to either double or string

    I have S9(13)V99 -COMP-3 format which I want to convert to either double or a string. Does any one knows how I can do it. I have browsed the net but did not find what I am looking for.
    If you have any code please post.
    Thanks in advance,

    You didn't say exactly where you have this data, but I GUESS you have it on some storage medium (written out by a COBOL program?).
    What does this data really look like? (I suspect you are going to have to figure out the format and then bit-fiddle.)

  • Can't convert an ArrayList into a Double

    I have this TXT file with some data that i read and insert it to an arraylist then i want to pass the data in to several variables but i keep getting an error when i convert it to double.
    TXT file:
    volvo
    200000
    0.7
    2000
    Mercedes
    500000
    1.0
    1000
    Fiat
    100000
    0.5
    5000
    Code:
    class Register{
    private ArrayList bilar = new ArrayList();
    private BufferedReader indata =     new BufferedReader(new InputStreamReader(System.in));
    //Read the information from .txt"
    public void läsInRegister() throws IOException{
    try
    FileReader file = new FileReader("C:/Users/Kelly/workspace/cla…
    BufferedReader buf = new BufferedReader(file);
    String in = buf.readLine();
    while (in != null && !in.equals(""))
    bilar.add(in);
    in = buf.readLine();
    System.out.println(bilar+ "\n" );
    catch (Exception e){
    public void set(){
    for(int i=0; i< bilar.size(); i++) {
    String str = bilar.get(i).toString();
    String modell = str;
    i=i++;
    str="";
    str = bilar.get(i).toString();
    // until here everything is allright
    // Now i have try with this ways but still nothing
    double inköpspris = Double.parseDouble(str);
    i=i++;
    double bränsleförbrukning = (double) bilar.get(i);
    i=i++;
    double underhåll = (double) bilar.get(i);
    i=i++;     
    double bränsleförbrukning = Double.parseDouble((String) bilar.get(i));
    i can convert it to string there is no problem there, so i tried to convert the string str to double but still keeps getting the same error
    the error is:
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at examples.Register.sortera(Bilkostnad.jav…
    at examples.Bilkostnad.main(Bilkostnad.java…

    They're not doubles, they are Strings, resulting from readLine() calls. You have to parse them into doubles. Your already doing that with one of them, just do it to the others. A trivial problem that you had already solved.

Maybe you are looking for

  • How to get compilations to show up as one album in Albums view

    In albums view, the NPR Austin 100 song compilations (1 folder with 100 songs) I imported to itunes show up as 100 different albums with 1 song each, which is a mess and makes finding and viewing my regular 10+ song albums difficult. Also I want to b

  • Folio Builder Panel: Error #3115

    can someone provide any more details what this eror means? It pops up after I start the Folio Builder Panel. After that: Spinning wheel on "Loading Folios". The error message dialog does not help at all. Installed the new Tools, uninstalled them alre

  • How do I get rid of clear history pop-up everytime I close a tab or page?

    Recently, I believe after updating to Firefox 33.1, I began to get a pop-up window for handling cookies,cache, browsing history,downloads etc. every time I close a page or tab. This is super annoying as I thought that I set-up those functions to be d

  • Currency in a prompt

    Hello, i've got problem. I need to made a sales raport. One of the column is price in currency- EURO. But i've got data in US dolars. I need to do a prompt on a dashbord when user can write value EURO for Dolar. The value should be taken to the rapor

  • Recordable Volume Change Control Number?

    Does any one know the midi control number that Garageband 09 uses to record volume changes on a software instrument track? I'm not talking about the standard Midi control number 7 for volume - this only controls the left-right fader in the track head