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

Similar Messages

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

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

  • Reduce the field value from three decimal places to two decimal places

    hi experts,
    plz help me with this
    actually i have to display the  value of the field MENGE in the list with two decimal places.
    but when i go and see the field menge in the table mseg it is having three decimal places.
    so could u plz suggest me how to solve this.
    regards
    siri

    Please try using the DEIMALS extension of the WRITE statement.
    data: menge type menge_D value '1234'.
    write:/ menge decimals 2.
    Regards,
    RIch HEilman

  • Double value truncated to two decimal places without rounding the value.

    I want to truncate double value to two decimal places without doing the rounding of the value.
    Is there any method which can directly do the truncation.

    There's many ways to achieve this such as using
    BigDecimal's setScale method or type-casting. This is
    the way I like to do it:double d = -5.239;
    d = d > 0 ? Math.floor(d * 100) / 100.0 : Math.ceil(d
    * 100) / 100.0;
    Your division by 100 may cause an rounding error, because there are numbers which no finite binary representation. That's splitting hairs! I know ;-)

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

  • How can I limit a double value to two decimal place?

    How can I limit a double value to two decimal place?
    Java keeps on adding zero's to a simple double subtraction:
    1497 - 179.64 = 1317.3600000000001The answer must have been simply: 1317.36

    If the trouble is with output ...
    If the trouble is with value accuracy ...The trouble is with OPs understanding of and/or expectations of IEEE 754 floating point numbers. o_O
    [And it's probably a view (output) issue.]
    how can i actually use numberformat to cut those
    unwanted decimal places?Read the API - Puce already provided the link.

  • Any function module to round of a value to two decimal places?

    Hi gurus,
    Any function module to round of a value to two decimal places?

    Hi,
    you can use FM 'ROUND'.
    Thanks.

  • How to correct a double value to two decimal places

    hi,
    How to correct a double value to two decimal places
    eg.
    double tt=100.100032
    i want to correct to 2 decimal places
    ie tt=100.10
    regards,
    jagan

    Check my other reply on the other thread. Please don't cross-post.

  • 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"));

  • 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();
    }

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

  • Two decimal places

    Hello, i want to have my results in my shop apllication in two decimal places. I tried DecimalFormat f = new DecimalFormat("#.##"); with import java.text.DecimalFormat; but it doesnt change the decimal places.
    And when i try this class example which i found on http://www.roseindia.net/java/beginners/RoundTwoDecimalPlaces.shtml it says that inner classes cannot have static declarations on public static void main(String[] args) {          and     public static float Round(float Rval, int Rpl) {
    Im using netbeans 5,5, does someone know what the problem is?
    public class RoundTwoDecimalPlaces{
    public static void main(String[] args) {
    float num = 2.954165f;
    float round = Round(num,2);
    System.out.println("Rounded data: " + round);
    public static float Round(float Rval, int Rpl) {
    float p = (float)Math.pow(10,Rpl);
    Rval = Rval * p;
    float tmp = Math.round(Rval);
    return (float)tmp/p;
    Edited by: javaboy on Nov 11, 2007 12:46 PM

    package view;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import controller.index;
    import model.product;
    import java.text.*;
    public class View_basket extends JPanel implements ActionListener{
         private static final long serialVersionUID = 1L;
         private index index;
         private JButton btnGoToPay;
         private JLabel[] lblProducts, lblPrices;
         private int countProducts;
         private int offset=40;          // # of pixels from the top
         private int increment=20;     // the next product will appear this amount of pixels below it's predecessor
         private JPanel container;
         public View_basket(index index){
              this.container = new JPanel(null);
              this.container.setName("Shopping basket");
              this.container.setBackground(new Color(151, 186, 225));          
              this.container.setSize(190,200);
              this.container.setLocation(550,20);
              this.index=index;
         public JPanel updateGui(){
              System.out.println("class view.View_basket.updateGui()");
              ArrayList products = index.basket.getProducts();
              countProducts = products.size();
              // if product basket is to big, resize the basket frame
              if(countProducts > 6){
                   this.container.setSize(190,(300+((countProducts-6)*10)));     
              lblProducts = new JLabel[countProducts];
              lblPrices = new JLabel[countProducts];
              JLabel lblTitle = new JLabel();
              lblTitle.setText("Winkelmand");
              lblTitle.setBounds(5, 5, 150, 20);
              lblTitle.setFont(index.FONT_12_BOLD);
              this.container.add(lblTitle);
              int teller=offset;
              double total=0;
              // walk trough all values from the arrayList
              for(int i=0; i < countProducts; i++){
                   product product = (product)products.get(i);
                   lblProducts[i] = new JLabel(product.toString());
                   lblProducts.setBounds(5, teller, 130, 20);
                   lblProducts[i].setFont(index.FONT_10_PLAIN);
                   this.container.add(lblProducts[i]);
                   lblPrices[i] = new JLabel("? "+ product.getPrice());
                   lblPrices[i].setBounds(140, teller, 150, 20);
                   lblPrices[i].setFont(index.FONT_10_PLAIN);
                   this.container.add(lblPrices[i]);
                   teller +=increment;
                   total += product.getPrice();
              // create total labels
              JLabel lblTotal = new JLabel("Totaal: ");
              lblTotal.setBounds(5, teller, 50, 20);
              lblTotal.setFont(index.FONT_10_BOLD);
              this.container.add(lblTotal);
              // create total labelseeuro
              JLabel lblTotalPriceeuro = new JLabel("? "+ total);
              lblTotalPriceeuro.setBounds(140, teller, 50, 20);
              lblTotalPriceeuro.setFont(index.FONT_10_BOLD);
              this.container.add(lblTotalPriceeuro);
    // create total labelsdollar
              JLabel lblTotalPricedollar = new JLabel("$ "+ total*1.45);
              lblTotalPricedollar.setBounds(140, teller, 50, 40);
              lblTotalPricedollar.setFont(index.FONT_10_BOLD);
              this.container.add(lblTotalPricedollar);
              int btnOffset = this.container.getHeight()-25;
              btnGoToPay = new JButton("Betalen...");
              btnGoToPay.setBounds(5, btnOffset, 180, 20);
              btnGoToPay.setFont(index.FONT_12_BOLD);
              btnGoToPay.addActionListener( this );     
              if(countProducts == 0)
                   btnGoToPay.setEnabled(false);
              this.container.add(btnGoToPay);
              return container;
         public void actionPerformed(ActionEvent event) {
              // if the pay button is pressed
              if(event.getSource().equals(btnGoToPay)){
                   ((View_pay) index.panelPay).updateGui();
                   index.showPanel("View_pay");

  • Rounding to two decimal places in BPC/NW

    Hello,
    I am dealing with the task to round values to two decimal places. I have found some discussions in BPC-MS where the statement ROUND should work in logic. Unfortunately I am not able to make it work in the NW version.
    Isn't there also a parameter in the appset or application administration which would cut the numbers only to two decimal places (this task would be also a possible solution for us).
    Thanks for any help
    Jan

    Hello Pravin,
    the second import worked fine. I realized that the class has changed to ZCL_BPC_SL_ROUND.
    I debugged the class and noticed that the parameter it_cv is not filled at all. Therefore the program ends before starting the rounding procedure. Here is the part of the code:
    Take CV into account
      clear l_success.
      loop at it_cv into ls_cv.
        clear l_val_string.
        loop at ls_cv-member into l_member.
          if sy-tabix eq 1.
            l_val_string = l_member.
          else.
            concatenate l_val_string l_member into l_val_string separated by ','.
          endif.
        endloop.
        if l_val_string ne space.
          l_success = add_dim_restriction( i_param = l_val_string i_dimension = ls_cv-dimension i_clear = abap_true ).
          if l_success eq abap_false.
            concatenate 'Failed to successfully add Dimension' ls_cv-dimension into l_log_msg
            separated by space.
            cl_ujk_logger=>log( l_log_msg ).
            cl_ujk_logger=>log( 'Exiting Round Method' ).
            cl_ujk_logger=>empty_line(  ).
            raise exception type cx_uj_custom_logic
              exporting messages = et_message.
            exit.
          endif.
        endif.
      endloop.
      if l_success eq abap_false. exit. endif. - here the program exits and therefore doesn't do any rounding.
    If I comment this part the system rounds correctly but runs on all records in the cube which degrades performance a lot.
    Could you please advice further if it is possible to restrict the data region only to the submitted data?
    Best regards
    Jan

  • Uploading Number with Two Decimal Places

    I am trying to import data from my excel file to table in the database using SQL Developer.
    It is working fine except that in my excel file I have data with two decimal places, but during import it shows only one decimal place. Is there any way I can import data with two decimal places?

    This works well with SQL Dev 1.5.X.
    Guess it would have been a bug in prior versions.

Maybe you are looking for

  • No monitors pulled for self defined logical component

    Hi, I have defined a system landscape in smsy and created solution landscapes in the sm. For some systems I had to create a new logical component. My problem: Although RFC destinations work fine, for all systems within the new logical component no mo

  • How can we download Mozilla Firefox 3.6.x?

    We are trying to access FAFSA (Federal Student Aid site) and FAFSA has detected a "connectivity with the Browser" problem. It recommends linking to a browser update. For our computer (Windows XP op sys) FAFSA says the suported browsers are 3.5.x and

  • IMSS Min Normalized Measure not appearing in imsmanifest.xml file

    Hello, The IMSS Min Normalized Measure line is not appearing in my imsmanifest.xml file. It used to, but since I upgraded to Captivate 5.5, I don't see it anymore. I have thoroughly checked my settings: Reporting is enabled SCORM 2004/Manifest/Defaul

  • Images getting corrupted in Lightroom 4.2

    I have experienced this aswell. As mentioned in: http://forums.adobe.com/message/4138626 and http://forums.adobe.com/thread/948417?tstart=0 My lightroom has after two weeks of playing with a fully working raw file corrupted it. This is what the photo

  • SAP on Oracle RAC+ASM 11g - SWPM installation Option

    Dear Experts, I came across SAP Note 1977393 which is describing the installation steps of a RAC installation with SWPM with an example. However, the note is not describing the exact preparation steps to be performed on the cluster nodes. For example