Formatting a Double to a String for Swing output

Hi, I'm new to Java and I'm working on a project with AWT & Swing. I'm trying to read in a user entered number, convert it to a double, work on it and then output the String value of the result with only two decimal places. The code I have is:
public void actionPerformed(ActionEvent e)
double result = 99;
double temp;
DecimalFormat newTemp = new DecimalFormat("#,###.00");
if (e.getSource() == bConvert1)
temp = (Double.parseDouble(tTemp1.getText().trim()));
result = (temp*1.8)+32;
newTemp.format(result);
tResult1.setText(String.valueOf(result));
else if (e.getSource() == bConvert2)
temp = (Double.parseDouble(tTemp2.getText().trim()));
result = (5.0/9)*(temp-32);
newTemp.format(result);
tResult2.setText(String.valueOf(result));
This is working for some values, but for some values entered, the result displayed is just the remainder.

The reason it doesn't always work could be because DecimalFormat (for reasons known only to Sun) uses ROUND_HALF_EVEN...
This means that you will have to round the value to the number of decimal places you require before calling format()
I use something like the following formatter class
class Formatter {
  public static final int DEFAULT_PRECISION = 2;
  public static final String DEFAULT_PATTERN = "#.00";
  public static final String ZEROS = "0000000000000000";
  public static String convertDoubleToString(Double d) {
    return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
  public static String convertDoubleToString(double d) {
    return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
  public static String convertDoubleToString(Double d, int precision) {
    return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
  public static String convertDoubleToString(double d, int precision) {
    return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
  public static String convertDoubleToString(Double d, String pattern) {
    return new DecimalFormat(pattern).format(d.doubleValue());
  public static String convertDoubleToString(double d, String pattern) {
    return new DecimalFormat(pattern).format(d);
  private static final double round(Double d, int precision) {
    double factor = Math.pow(10, precision);
    return Math.round((d.doubleValue() * factor)) / factor;
  private static final double round(double d, int precision) {
    double factor = Math.pow(10, precision);
    return Math.round((d * factor)) / factor;
}

Similar Messages

  • Formatting a Double to 2 decimal places without first converting to String

    Hi,
    Does anyone have any clear idea on how to format a Double directly without first converting it
    to a String.I have just read through DecimalFormat/NumberFormat but I think there might be an easier way.I am also aware of printf(%f) and format(%f),but unfortunately am using Java 1.4 at the moment which does not seem to support them(will upgrade soon).The code I have is as follows:
    public void displayAnalysis ()
           System.out.println ("========================================================================");
           System.out.println ("========================================================================");
           System.out.println ("\nANALYSIS RESULTS FOR FILE " + inputFile + " \n");
           System.out.println ("========================================================================");
           System.out.println ("========================================================================");
           System.out.println ("\nString length: "+ inputText.length());
           System.out.println ("Ratio of printing to non-printing characters: "+ pRatio);
           System.out.println ("Ratio of vowels to consonants: "+ vRatio);
           System.out.println ("");
           System.out.println ("Frequency of vowels as a percentage of number of printing characters;");
           System.out.println ("Percentage of a's ="+ (NumberFormat.format(new DecimalFormat(((double)frequency[0]*100)/printable)))));
           System.out.println ("Percentage of e's ="+ ((double)frequency[1]*100)/printable + "%");
           System.out.println ("Percentage of i's ="+ ((double)frequency[2]*100)/printable + "%");
           System.out.println ("Percentage of o's ="+ ((double)frequency[3]*100)/printable + "%");
           System.out.println ("Percentage of u's ="+ ((double)frequency[4]*100)/printable + "%");
           System.out.println ("Number of whitespace characters were " + whitespace);
           System.out.println ("");
           System.out.println ("========================================================================");
           System.out.println ("========================================================================");
           System.out.println ("");
           System.out.println ("");
       }I would like to display the frequencies to 2 decimal places.As a last resort I will have to alter the code to use DecimalFormat,but I'm hoping someone has a simpler solution.

    Oops,please ignore the line for the first frequency (a's),I was just playing around with trying to use NumberFormat!

  • Java.util.Formatter format string for week of year?

    What is strange in the Formatter API, regarding dates, is that there is no format string to display week of year. To display day of year e.g. you can use:
    String.format(�%tj�),Calendar.getInstance())but what is the string for week of year?
    String.format(�%tw�),Calendar.getInstance())doesn�t work.
    Any ideas, or did I overlooked the API?

    I �m using
    String.format(�%tx�),Calendar.getInstance())everywhere in my code where x is any of the other (e.g. j, d etc.). Why use different way for this? How come Sun did�t add e.g. a w in the API to display the week of year as it does for day of year?

  • Match the string for a particular format

    i want to chek the string for a particular format..
    lets say for ex ,
    i have to check the string for 6A1N format where A - Alphabets and N - Numbers.
    that means my string exactly contains 6 alphabets from a to z and one number from 0 to 9
    like this i want to check for two more fromats..they are..
    2A7N1A or
    9N1A

    koneru9999 wrote:
    will the pattern is helpful in my case?
    and i don't have any idea doesn't mean finsh reading all the API right?You need to study http://www.regular-expressions.info/ and then http://java.sun.com/docs/books/tutorial/essential/regex/ .

  • How can I format the double value?

    Hi,
    I am trying to format the double variable as like,
    double var = 1234.56789
    but i want that variable as like var = 1234.56
    How can i do that in java?
    Please help me.
    From
    Parshuram Walunjkar

    Try something like the following, assume the variable 'd' underneath is your double value that you want to format.
    double d = 4.45678;
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(5);
    nf.setMinimumFractionDigits(5);
    String number = nf.format(d);
    Then use the string "number" for printing out.

  • How to double space in Pages for iPad?

    How to double space in Pages for iPad?

    Double spacing is double spacing whether you are using Pages or Word. Double spacing is dependent upon the font size that you are using in the document no matter which word processing app that you use.
    Pages on the iPad has limited fonts and chances are pretty good that if you import a Word file into Pages on the iPad, there will be some formatting or font issues.
    But once again, Helvetica in Pages is pretty much the same Helvetica as you would be using in Word. If you use a font in Word that is not available in Pages, you will see a warning message that some elements of the original document have been changed.

  • EBS search string for check number

    Hello Gurus
    My client is using MT940 FORMAT for EBS,requirement is in a bank statement we are having 10 transactions which are having the same amount for ex:rs.1000 for ten payment transactions. now system is not able to post the document when we import the bank statement.
    I wanted to use search string for check number,  note to payee in bank statement is check number.Please find the below refference
    /EI/400229001       010013
    0000010013
    Reference 010013
    How could i use search string for this i tried but im not getting the solution im getting the following error difference is too large F5 263.
    Appreciated for our help............
    Thanks a lot in advance...............

    Hi Paulo,
    Thanks for the reply. However i have the following setting and it still does not work..
    Mapping -> AB01
    When i do the simulation it shows the Number and the hits and mapping.
    In the Seach String use i have following settings:
    CC 1000
    Interpretation : ALL Interpretation
    Search String : TEST1 ( this is the name that i gave to above search string)
    Target : Posting RUle
    Active checked.
    But still when i upload the bank statement it is posting to Rule AB03 and not AB01
    Also when i try FEBSTS it says no document hits ???
    Your answer is greatly appreciated.

  • Help with today's date - 2 days as a string for a file name

    This will be an Expression/Connection String for a Flat File Connection Manager.
    Need it in this format COMPANY20150402.txt except the formula needs to incorporate the DATEADD("D", -2, Getdate())
    "COMPANY" + (DT_STR,4,1252) DatePart("yyyy",getdate()) +
    Right("0" + (DT_STR,4,1252) DatePart("m",getdate()),2) +
    Right("0" + (DT_STR,4,1252) DatePart("d",getdate()),2)  +".txt"
    Where do I add the DATEADD part? and be syntactically correct?
    TIA
    Harry

    You do get COMPANY20150402.txt outputted from your expression
    just keep adding DATEADD("DAY",-2,.... to each getdate()
    like
    "COMPANY" + (DT_STR,4,1252) DatePart("yyyy",DATEADD("DAY",-2,getdate())) +
    Right("0" + (DT_STR,4,1252) DatePart("m",getdate()),2) +
    Right("0" + (DT_STR,4,1252) DatePart("d",getdate()),2)  +".txt"
    Arthur
    MyBlog
    Twitter

  • Scan string for "returns"

    Hi,
    I have a multi lined string and want to put it as list into a listbox (i
    did it with a for loop and the "i"attached to the line index of the
    "pick line" vi) but now a have let my for loop know how many rounds it
    must do! How can scan a multi lined strings for "number of lines"?
    Regards Thijs

    Thijs,
    Use the "Spreadsheet String to Array" function (in string functions). Wire
    it as follows:
    format string: string constant containing "%s"
    spreadsheet string: your string
    array type: (empty) array string constant
    delimiter: string constant containing enter ("\n" with string in code
    display mode)
    The output "spreadsheet" is an array with strings that can be wired to the
    attribute node of the listbox.
    Important notice: \n is not the same as \r ! If your string comes from a
    ..txt file, this can cause unexpected results!
    Regards,
    Wiebe Walstra.
    AIR technical Automation.
    By the way, Thijs. If your in the Nederlands, maybe you'd like to visit our
    annual LabVIEW meeting, PierVIEW. This also applies to the rest of the
    group. Check out www.air.nl, and follo
    w PierVIEW 2001.
    AIR technical Automation
    www.air.nl
    "Thijs Boeree" wrote in message
    news:[email protected]..
    Hi,
    I have a multi lined string and want to put it as list into a listbox (i
    did it with a for loop and the "i"attached to the line index of the
    "pick line" vi) but now a have let my for loop know how many rounds it
    must do! How can scan a multi lined strings for "number of lines"?
    Regards Thijs

  • Please Help!! How to get the width of the String for print out?

    Hi there,
    I need to do some printing in my application. I just want to know how can I get the width of the string when it is printed on the paper.
    I have tried to use the following code to get the width
    Rectangle2D rec = font.getStringBounds(str, new FontRenderContext(null, true, true));
    double width = rec.getWidth();
    however, the width I got from that function is not correct (the returned width is longer than the printed one)
    Does anyone know how to solve this problem?
    Thank you and Happy New Year !

    hi,
    The getFontMetrics(Font) is also defined in the Component class and therefore you can retrieve it even if you dont override the paint method.
    try the following (provided ur code extends some class that extends Component indirectly)
    FontMetrics f = this.getFontMetrics(this.getFont());
    int width = f.stringWidth(str); //str is the String for which u need to check the width.
    hope this was useful
    happy holidayz

  • Encoded double byte characters string conversion

    I have double byte encoded strings stored in a properties file. A sample of such string below (I think it is japanese):
    \u30fc\u30af\u306e\u30a2
    I am supposed to read it from file, convert it to actual string and use them on UI. I am not able to figure how to do the conversion -- the string contains text as is, char backslash, char u, and so on. How to convert it to correct text (either using ai::UnicodeString or otherwise)?
    Thanks.

    Where did this file come from? Some kind of Java or Ruby export? I don't think AI has anything in its SDK that would natively read that. You could just parse the string, looking for \u[4 characters]. I believe if you created a QChar and initialized it with the integer value of the four-character hex string, it would properly create the character.

  • Next Double from a String

    I have used a Scanner Object before to read doubles from an input, but how do I get the Next double from a String?
    Used this in the past:
    Scanner input = new Scanner(System.in);
    double num = input.nextDouble();I am looking for something like this:
    String example = "100.00";
    double num = example.nextDouble();Any suggestions?

    Specifically a String like this "50.05text", where it will drop the "text" part. and only return 50.05.

  • Formatting a double

    Hello,
    I have a problem with formatting a double.
    Suppose we have a double:
    double x = 25.665478962
    I want to round this to a double with 2 decimals:
    thus: x has to be 25.67
    How can I do this???
    Thanks,
    Daniel

    Hi Daniel,
    Do you know about the classes "java.text.DecimalFormat" and "java.lang.Math"? Are they not suitable for you? Have you seen this:
    http://java.sun.com/docs/books/tutorial/java/data/numbers.html
    Hope this helps you.
    Good Luck,
    Avi.

  • Store Date as Oracle Date as string for simplicity?

    I got this table (scaled-down):
       CREATE TABLE TBLSERVICES
         STORENBR CHAR(4 byte) NOT NULL,
         SERVICEDATE CHAR(10 byte) NOT NULL,
         CHECKNBR CHAR(6 byte),
         ORDER_START_TIME DATE NOT NULL,
         ITEMID CHAR(4 byte), 
         SERVERID NUMBER(18),
         SERVERNAME VARCHAR2(50 byte),
         ITEMQUANTITY NUMBER
    ) Function MakeServicesDatatable(byval onodesconfig as xmlnodelist) return datatable
           dim objDT as new datatable
           With objDt
                .Columns.Add("StoreNbr", GetType(String))
                .Columns.Add("Order_Start_Time", GetType(String))
           End With
           dim dte as string
           For Each onode As XmlNode In onodesConfig
                    If onode.InnerText = "5" Or onode.InnerText = "6" Then
                        objdr = objDt.NewRow
                        objdr("StoreNbr") = storenbr
                        dteYear = parentNode("Order_Start_Time").SelectSingleNode("Year").InnerText
                        dteMonth = parentNode("Order_Start_Time").SelectSingleNode("Month").InnerText
                        dteDay = parentNode("Order_Start_Time").SelectSingleNode("Day").InnerText
                        DteHour = parentNode("Order_Start_Time").SelectSingleNode("Hour").InnerText
                        dteMin = parentNode("Order_Start_Time").SelectSingleNode("Minute").InnerText
                        dteSecs = parentNode("Order_Start_Time").SelectSingleNode("Second").InnerText
                        dte = String.Format("{0}/{1}/{2} {3}:{4}:{5}", dteMonth, dteDay, dteYear, DteHour, dteMin, dteSecs)
                        objDR("order_start_time") = dte
                        objDt.rows.add(objdr)
                    end if
            next onode
            return objDT
    end function
    I call following:
    dt = MakeServicesDatatable(NodesWithData)
    WriteDataToDB(dt)
    Public Sub WriteDataToDB(ByVal dtServices As DataTable)      
            Dim altConnString As String = connString
            Dim queryString As String = "Select * from tblServces"
            Using connection As New OracleConnection(altConnString)
                Dim adapter As New OracleDataAdapter()
                adapter.SelectCommand = New OracleCommand(queryString, connection)
                Dim builder As OracleCommandBuilder = New OracleCommandBuilder(adapter)
                connection.Open()
                Dim ds As DataSet = New DataSet
                adapter.Fill(ds, "tblServices")
                For Each drService As DataRow In dtServices.Rows
                    ds.Tables("tblServices").ImportRow(drService)                
                Next drService
               adapter.Update(ds, "tblServices")
            End Using
        End SubIn a PL/SL SQL Query, I need to say something like this:
    - Lunch is anything before 3:00pm
    - Assume date is same as date of order start time
    select  storenbr,
            itemquantity
    from tblServices
    where order_start_time < DatePArt(order start time date) || 15:59:00 I don't know syntax for getting date portion of oracle date
    Problem is the order_start_time is stored as dd-mmm-yyyy.
    I need seconds also. Should I make order-start_time a string
    and convert to date in SQL statement.

    Hi Vinod,
    Create a varaible of type customer exit for RUNDATE.
    IF i_step = 1.
       select max (rundate) from /bic/prundate into zrundate.
      IF i_vnam = 'rundate'.
      l_s_range - low = zrundate.
      l_s_range- opt = 'eq'.
    append l_s_range into e_t_range.
    endif.
    Endif.
    hope it helps
    bhaskar

  • Converting my double to nice String

    Hi,
    I am doing a calculation as follows
    double x = 12102012 + 2400000.5
    System.out.println(Double.toString(x));
    Now I want it to display the nice readable format of 14502012.5
    instead I get this 1.45020125E7
    How can I stop this happening?

    The output is stored as a double. You are asking for special output formatting, and you get that by using an instance of NumberFormat. DecimalFormat is probably nicer to use.
    Many examples of different formats here:
    http://javaalmanac.com/egs/java.text/FormatNum.html

Maybe you are looking for