Formatting Strings to two decimal places

When formatting double amounts to two decimal places, I looked up the procedure online and I have this so far:
     public void calculatePayments()
          double monthlyInterestRate = (Double.parseDouble(interestBox.getText())/12)/100;
          double amountOfLoan = Double.parseDouble(balanceBox.getText());
          double numberOfPayments = Double.parseDouble(yearsBox.getText()) * 12;
          DecimalFormat Currency = new DecimalFormat("0.00");
          double paymentAmount = (amountOfLoan * monthlyInterestRate) / (1 - Math.pow(1/(1 + monthlyInterestRate),numberOfPayments));
          double formattedAmount = Currency.format(paymentAmount);
          String s = Double.toString(paymentAmount);
          tableBox.append(s);
          tableBox.setText("Payment" + "\n" + "Number" + "\n");
          for(int i = 0; i <= numberOfPayments; i++)
                    tableBox.append("" + i + "\n");
However, I get the following:
ProgramInterface.java:134: incompatible types
found : java.lang.String
required: double
          double formattedAmount = (Currency.format(paymentAmount));
I'm trying to append the number to a text box (I'm making a loan calculator for my 155 class) Thanks for the help

String s = Currency.format(paymentAmount);Next time please paste your code between code tags exactly like this:
&#91;code&#93;
your code
&#91;/code&#93;
You can do that by simply pasting your code in the message area, highlight it and then click on the code button above.
You may read the [url http://forum.java.sun.com/help.jspa?sec=formatting]Formatting tips for more information.
Regards

Similar Messages

  • Is it possible to convert a float to two decimal places

    Can anyone help me to convert a float to two decimal places
    float f=16;
    System.out.println(f);
    It will print 16.0
    But I want to get printed as 16.00

    "convert" no, as no conversion is needed, obviously. Format the output, yes. Read the API for String and its printf method.

  • How to take float precision to two decimal places?

    Hi, everybody:
    I'm a straight noob...first week in Java programming. Before you bash me for not checking FAQs and such, believe me, I have.
    I have tried BigDecimal movePointLeft, but I don't know how to construct it using proper syntax. I also tried currency and toString but I keep messing up my syntax somehow. Four hours into this and nothing is working.
    Here is the problem: I have a float. I want to format its output to two decimal places, trying to achieve in Java what C would produce as:
    printf("The amount you owe is $%.2f", fltAnyName);
    Any help would be appreciated.
    Thanks,
    Rob

    Sorry, guys. I have tried both recommendations and I can't get either to work. I'm getting a compile error pointing to the delineating period between the "out" and "printf" when I try the C-like code. I have 1.5, too. I know your advice is sound so I must be doing something wrong. Can you insert the code DecimalFormat code that will correct this problem where it needs to go? The packages below have been included becasue of all the different solutions I have attempted.
    import java.io.*;
    import java.math.*;
    import java.text.*;
    import java.lang.*;
    public class CoinCalculator2
         public static void main(String[] args) throws IOException
              String strQuartes, strDimes, strNickels, strPennies;
              int intQuartes, intDimes, intNickels, intPennies;
              float fltValue;
              BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("THE COIN CALCULATOR");
              System.out.println();
              System.out.print("Enter the number of quarters you have: ");
                   strQuartes = dataIn.readLine();
                   intQuartes = Integer.parseInt(strQuartes) * 25;
              System.out.print("Enter the number of dimes you have: ");
                   strDimes = dataIn.readLine();
                   intDimes = Integer.parseInt(strDimes) * 10;
              System.out.print("Enter the number of nickles you have: ");
                   strNickels = dataIn.readLine();
                   intNickels = Integer.parseInt(strNickels) * 5;
              System.out.print("Enter the number of pennies you have: ");
                   strPennies = dataIn.readLine();
                   intPennies = Integer.parseInt(strPennies);
              fltValue = (intQuartes + intDimes + intNickels + intPennies) / 100;
              System.out.println();
              System.out.println("The value of your coins is $" + fltValue);
              System.out.println();
    }

  • Rounding off to two decimal places

    Hello,
    For simplicity, is there a method which will round off
    a double variable to two decimal places.
    Excample: if I have a result which equals 2.1999998
    and I want to display this as 2.20 in a TexTField.
    Any help would be much appreciated.
    Thanks

    If you are trying to do dollars and cents, I further recommend you use:NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
    String currencyOut = currencyFormatter.format(yourNumber);to format your numbers as they will give the correct precision for international currencies simply by setting the locale, and they will also automatically handle the currency symbols ($, DM FR, etc.)
    Doug

  • Printing to two decimal places on the screen

    Hi everyone...
    I am using mysql as my DB...my field is declared there as decimal(8,2) means to 2 decimal place..when i am getting the result i also need to print to 2 decimal place...
    so when i do(rs.getDouble("Price")) it is not printing as two decimal place...how do i get it to print to 2 decimal place...
    Thanx a lotttttt

    javax.text.DecimalFormat dfrm t=new java.text.DecimalFormat("#0.00");
    //or another format see API doc for DecimalFOrmat
    String result = dfrm.format(rs.getDouble("Price"));

  • Need only two decimal places, but BigDecimal isn't working

    Hello again. This time I've got a problem with getting only two decimal places. I tried using BigDecimal but when I compile it, I get an error "cannot find symbol class BigDecimal" and a "cannot find symbol variable BigDecimal".
    Grrr... I just want my value to have only 2 decimal places before it ends up in my text field.
    Any help will be appreciated.
    - Phonse
    if (ostuff1.equals("amt tendered"))
                     finalamt = total1 * 1.12;
                     change = cash1 - finalamt;
               BigDecimal finalamt2 = new BigDecimal(finalamt);
                  finalamt2 = finalamt2.setScale(2, BigDecimal.ROUND_DOWN);
                  BigDecimal change2 = new BigDecimal(change);
                  change2 = change2.setScale(2, BigDecimal.ROUND_DOWN);
                  finalamt = doubleValue(finalamt2);
                  change = doubleValue(change2);
                     addItem(String.format("Amount Tendered:          "+"P "+finalamt));
                     addItem(String.format("Change:                     "+"P "+change));
                   }

    @ georgemc
    Isn't it better to import whole packages instead so
    you can have everything available when you call them?
    I mean, it's kinda hard to import individual classes
    everytime you need to call them.No. You can get conflicts when importing complete packages. If you importjava.awt.*;
    java.util.*;and then declareList list;the compiler does not know which List you meant, java.util.List or java.awt.List.
    Offtopic @ prometheuzz
    LOL. When I was a kid still playing my Playstation I
    wanted to have a career in computers when I got to
    college. Now I'm 14 and a 3rd year high school
    student and I just got a reality check -- computers
    just isn't for me. And alot of those professionals
    say Java is the "easiest" programming language. O_O
    Meh. I'll just follow my other dream of becoming a
    chef. Just seems like my parents won't like it...
    Bleh... Two more years... Two more years...Sure, but if you like programming, work (hard) for it. Most people have to work hard in order to become good at something, no one is born as a programmer. This goes for becoming a chef as well.

  • Result to two decimal places

    Hi I have the following code for currency conversion, now I want that when a converted currency result is for example 1.8 it displays 1.80 ie to two decimal places. how is this done? thanks
    private void converteurosButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                  
    //Parse Euros as a double and convert to GBP.
        DecimalFormat df = new DecimalFormat("#,###.##");
        double gbp = (double) (Double.parseDouble(eurosTextField1.getText())) * 0.796345;       
        convertedeurosLabel.setText("� "+df.format(gbp));

      private static DecimalFormat format = new DecimalFormat("0.00");
      private String format(double value) {
        return format.format(value);
    // call  as
    format(2.999);

  • Number formatting with either 2 decimal places or none

    Hello,
    I'm using Acrobat 8 in XP and not familiar with Javascript.
    I have some dollar amount fields where I need it to be number formatted, and limited to 2 decimal places but leave the user the ability to enter only an integer.
    ie, go to two decimal places if any of
    > .
    > .0
    > .00
    > .000(...)
    are present but leave it off if none are present.
    I assume I need a custom format script but I've not been able to learn enough to figure it out yet.
    If anyone can give me some code I can edit and paste, that would be great. Any help is appreciated.

    > Have a String as "3.0000000"
    String s = "3.0000000";
    System.out.printf("%.2f", Double.parseDouble(s)); // 3.00
    Formatting - Numbers and Currencies
    ~

  • Trunc percentage two decimal places

    I have a report that has the option of dispalying pdf or excel. I have the pdf version working fine but i am having a little trouble on the excel version. I have a grand total and department total. Basically I need help formating two decimal places. Both dept_total and grand_total are numbers that both display. I have another column that displays what percent of the total is from each dept.It currently returns a number such as 10.23383547957459973 which i need to display as 10.23 How can i incorporate the trunc function into this code?
    ...to_char((dept_total/grand_total) *100)
    The query looks similar to this.
    select
    to_char(a._grand_total)
    ,to_char(a.dept_total)
    ,to_char((dept_total/grand_total) *100)
    from(
    select sum(xxxx) grand_total,
    sum(xxxx) dept_total
    from table)a

    Hi,
    Since you're calling TO_CHAR anyway, you can add a 2nd argument, specifying two decimal places:
    select
         a._grand_total
    ,     a.dept_total
    ,     to_char ((dept_total/grand_total) *100,       '999999999.99')     AS pct
    from     (
             select  sum (xxxx) grand_total,
                      sum (xxxx) dept_total     -- Why have two copies of the same value?
             from    table
         )a If you're not using a 2nd argument, why use TO_CHAR at all in this query?
    This will round the value, not truncate it. That is, if the value is 10.23<b>5</b>83547957459973, it would display '10.2<b>4</b>', not '10.2<b>3</b>'. If you always want to round toward 0 (rather than to the nearest multiple of .01), then use TRUNC.

  • Storeing values in floate data type upto two decimal places

    Hi
    I want a float type field in my table but want to store value up to two decimal places.
    so what syntax i need to follow plz suggest.
    thanks

    it is not possible to store with Number datatype. if you are using the data to sho report, then change its format (like 45 to 45.00). if you want to store 45.00 in database, then you have to modify the datatype for that column. for this follow the following path
    1. Add a column of datatype Varchar2.
    2. Copy all the value of your number field to it.
    3. Drop the old column.
    4. However make sure that if you have used that column somewhare in arithmetic calculation, the modify it and use to_number function to do arithmetic opration.

  • Convert amount with four decimal places to amount with two decimal places

    Hi,
    for specific reasons we have set the prices to four decimal places. However, in an invoice the staff needs to see all prices with two decimal places. Therefore I have created new user-defined fields which should show the rounded values However, I have not yet found the right formatted search that outputs the value with two decimal places including currency symbol.
    The statement 
    SELECT $[$38.20.NUMBER]
    outputs the value with two decimal places which is fine, but it does not contain the currency.
    The statement
    SELECT $[$38.20.0]
    outputs both value and currency, but the value still has four decimal places as the original price.
    And the statement
    SELECT CAST($[$38.20.NUMBER] AS VARCHAR(20)) + $[$38.20.CURRENCY]
    outputs a value with even six decimal places.
    Did anyone already have the same problem???
    Or does anyone have any idea???
    Thanks and regards
    Corinna

    Hi again,
    the value should be displayed in a user-defined field of the screen.
    The result of the query
    SELECT $[$38.20.NUMBER]
    has already two decimal places, so that I do not need a round here. But the currency is missing.
    When I add the round function to the query
    SELECT $[$38.20.0]
    it does unfortunatly result in an error.
    Any ideas????
    Thanks so much in advance!

  • Rounding off a float to two decimal places

    I want to make a function where I shall pass a float and and integer.
    The float shall have to be rounded off to a value in the integer.
    Can anyone please suggest how to round off a float.
    E.g.: if the float is 12.56890 and I want to round it off to 2 decimal places, then it should be 12.57.
    Regards
    Hawker

    I didn't mention any datatypes like float, double.True, but that is what the question is about, so you weren't answering the question. For a change.
    As I mentioned, that was just a mathematical steps to round of the floating point value. (Not in any programming languages point of view).False. You didn't mention that at all.
    This is the code for that in java.So here you are mentioning datatypes and floats for the same piece of mathematics that you have already been told, with reasons, doesn't work in floating point.
    which seems to be working fine
    Seems to. What evidence do you have that the float actually got rounded? As opposed to got displayed as rounded? Which is not what the OP asked for.
    And of course all that code seems to do is round 0.01 to two decimal places, which again is not what the OP asked for.
    For any remaining fans of this 'technique', please explain the behaviour of the following code:
         public static void     main(String[] args)
              int     count = 0, errors = 0;
              for (double x = 0.0; x < 1; x += 0.0001)
                   count++;
                   double     d = x;
                   int     scale = 2;
                   double     factor = Math.pow(10, scale);
                   d = Math.round(d*factor)/factor;
                   if ((d % 0.01) != 0.0) // if 'd' really has been rounded this should be zero
                        System.out.println(d % 0.01);
                        errors++;
              System.out.println(count+" trials "+errors+" errors");
         }

  • Help!printing float values with two decimal places

    hi there java pips! im a newbie to this technology so forgive me for this really stupid question....i would like to perform mathematical operations on two float values....the problem is i want to print them in a standard format and that is i want them to be displayed with two decimal places (e.g 190.00, 12,72, 1,000.01) how can i do this?

    Try java.text.DecimalFormat
    NumberFormat nf = new DecimalFormat("0.00");
    System.out.println(nf.format(x));

  • Printing two decimal places from BigDecimal values

    I am using BigDecimal to represent money values. My output needs to line up so that (with a non-proportional font) the decimal point and the two decimal places are in the same columns for each line. But when the dollar value has zero cents, or has a number of cents that is divisible by ten, it drops the trailing zeroes, and drops the decimal point if the decimal places are both zeroes. For example, I want to see "25.00" instead of "25" and "25.50" instead of "25.5". It doesn't seem to make any difference if I set the scale to 2. (I have resorted to getting the toString() of the BigDecimal and hacking the string before I display it, but surely there must be an easier way?)
          BigDecimal aaa = new BigDecimal("25");
          BigDecimal bbb = new BigDecimal("25.0");
          BigDecimal ccc = new BigDecimal("25.00");
          BigDecimal ddd = new BigDecimal("25.5");
          BigDecimal eee = new BigDecimal("25.50");
          BigDecimal fff = new BigDecimal("25.75");
          aaa.setScale(2);
          bbb.setScale(2);
          ccc.setScale(2);
          ddd.setScale(2);
          eee.setScale(2);
          fff.setScale(2);
          System.out.println("SCALE SET TO 2: ");
          System.out.println("aaa = " + aaa);
          System.out.println("bbb = " + bbb);
          System.out.println("ccc = " + ccc);
          System.out.println("ddd = " + ddd);
          System.out.println("eee = " + eee);
          System.out.println("fff = " + fff);produces this output:
    SCALE SET TO 2:
    aaa = 25
    bbb = 25.0
    ccc = 25.00
    ddd = 25.5
    eee = 25.50
    fff = 25.75Thanks,
    Martin

    Thankyou Dr. Clap. This solved my problem - I added an LHS to the setScale statements:
          aaa = aaa.setScale(2);
          bbb = bbb.setScale(2);
          ccc = ccc.setScale(2);
          ddd = ddd.setScale(2);
          eee = eee.setScale(2);
          System.out.println("SCALE SET TO 2: ");
          System.out.println("aaa = " + aaa);
          System.out.println("bbb = " + bbb);
          System.out.println("ccc = " + ccc);
          System.out.println("ddd = " + ddd);
          System.out.println("eee = " + eee);produced:
    SCALE SET TO 2:
    aaa = 25.00
    bbb = 25.00
    ccc = 25.00
    ddd = 25.50
    eee = 25.50

  • Round to two decimal places

    my cost per month textbox typically returns multiple decimal places, is it possible to limit it's output to two decimal places like real monetary calculations?
    calculatebutton.addEventListener(MouseEvent.CLICK, doMyCalculation);
    calculatebutton2.addEventListener(MouseEvent.CLICK, doMyCalculation2);
    costpermonth.restrict = ".0-9";
        var myAnswer : Number;
        myAnswer = Number(costofitem.text) - Number(amountsaved.text);
        amountneedtosave.text = String(myAnswer);
    function doMyCalculation2(e:MouseEvent):void
        var myAnswer2 : Number;
        myAnswer2 = Number(amountneedtosave.text) / Number(howmanymonths.text);
        costpermonth.text = String(myAnswer2);

    use the toFixed() method of numbers:
    amountneedtosave.text = myAnswer.toFixed(2);

Maybe you are looking for

  • Migration problem, Jdev 11.1.1.4.0 to Jdev 11.1.2.3.0

    Hi, I need Help, I've tried to migrate my aplication developed in Jdev 11.1.1.4.0 to Jdev 11.1.2.3.0, when deploy the application to Integrated weblogic Server 10.3.5 getting te next error: ------------------------------------------------------------

  • How do I select a color range like in Photoshop OR copy/move a layer into the mask of another layer?

    Hi there, I'm trialling Photoshop Elements and wanting to use a black and white (grey scale) layer that I've made as a mask in another layer and don't know how to do it in Elements.  In Photoshop, I'd do this (there maybe a better way in PS to do it,

  • Graphical errors when using Catalyst

    I have trouble with using the proprietary driver for my AMD RADEON HD 6970 gpu. After following instructions on the wiki, everything runs reasonably well, except: - Inside my DE, the wallpaper seems to be missing in various occasions. For example, it

  • Freight charges on return delivery

    Hi, How freight chargers are reversed while doing 161 mvt type. Is there any separate mvt required to return freight charge. How do we handle this plz clarify me.... BR Vel Note :Please search forum,subject is widely discussed in various threads in t

  • URL Link to Specific SWF Slide

    Is it possible once a Captivate 2 project has been exported to HTML/SWF to have a URL link open the SWF file to a specific slide number? For example if a Captivate 2 project is 20 slides long, the user could click a link that would open the swf file