Results 1 to 4 of 4

Thread: String/Number formatting

  1. #1

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Resolved String/Number formatting

    How can I format a number in java so that only two numbers are displayed after the decimal point?

    I have tried using DecimalFormat with no luck.

    Here is the code I used.
    Code:
    float newTotPrice = totPrice + Double.valueOf(myProduct.getPrice()).floatValue();
    //For formatting a number
    DecimalFormat df = new DecimalFormat("#.00");
    //Format 'newTotPrice' so that only two digits are shown after the decimal point
    df.format(newTotPrice);
    //Show total price
    lblTotPrice.setText("£ " + newTotPrice);
    This doesn't work as I got a result of "£ 509.97003"
    Last edited by x-ice; Mar 27th, 2008 at 11:49 AM.

  2. #2
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: String/Number formatting

    Code:
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    
    
    public class Util {
    
        public static void main(String[] args) {
    	double d = 10.45;
    	NumberFormat formatter = DecimalFormat.getNumberInstance();
    	formatter.setMaximumFractionDigits(2);
    	System.out.println(formatter.format(Math.PI));
        }
    }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  3. #3

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: String/Number formatting

    When the number of more than 999 the formatter seems to put a comma in. How can I set it so that it doesn't do this?

    E.g. 1,023.23 should be 1023.23

  4. #4

    Thread Starter
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: String/Number formatting

    Code:
    formatter.setGroupingUsed(false);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width