Results 1 to 6 of 6
  1. #1
    camaro01 is offline Member
    Join Date
    Jan 2011
    Posts
    52
    Rep Power
    0

    Default Quick question about numbers and decimals

    Guys,

    I completed a project for school but I am having a little problem formatting numbers.

    I have the following line

    Java Code:
    JOptionPane.showMessageDialog(null, "Subtotal: " + subTotal);
    The line and the code works but my problem is the result it yields has too many decimals. I tried the following line but it did not work:
    Java Code:
    JOptionPane.showMessageDialog(null, "Subtotal: %5.2f" , total);
    I tried placing the %5.2f outside the parenthesis and it did not work.

    Can someone help me fix this error?

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,785
    Rep Power
    7

    Default

    You need to use the String.format method.
    Java Code:
    JOptionPane.showMessageDialog(null, "Subtotal: " + String.format(......, subTotal));
    Or you can use the NumberFormat/DecimalFormat classes.

  3. #3
    camaro01 is offline Member
    Join Date
    Jan 2011
    Posts
    52
    Rep Power
    0

    Default

    I tried using the following String format but it gives me an error:

    Java Code:
    Shop.java:61: illegal start of expression
    			JOptionPane.showMessageDialog(null, "Subtotal: " + String.format(%5.2f, subTotal));
    			                                                                 ^
    1 error
    Any idea what I am doing wrong?

  4. #4
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    String.format requires a String as the first argument. %5.2f is not a String, but "%5.2f" is.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Java Code:
    JOptionPane.showMessageDialog(null, "Subtotal: " + String.format([color=red][b]"%5.2f"[/b][/color], subTotal));

    "%5.2f" is the format string.

  6. #6
    camaro01 is offline Member
    Join Date
    Jan 2011
    Posts
    52
    Rep Power
    0

Similar Threads

  1. quick question
    By biggerthanblue in forum New To Java
    Replies: 2
    Last Post: 04-10-2011, 04:33 AM
  2. Really Quick question
    By Ryan10 in forum New To Java
    Replies: 63
    Last Post: 03-02-2011, 02:11 AM
  3. Really quick question
    By shadycharacter in forum New To Java
    Replies: 2
    Last Post: 04-22-2010, 10:06 PM
  4. Formatting numbers or decimals (around comma)
    By Joris in forum Advanced Java
    Replies: 1
    Last Post: 04-22-2010, 05:46 PM
  5. Quick question
    By sAntA199 in forum New To Java
    Replies: 2
    Last Post: 12-09-2009, 03:01 AM

Posting Permissions

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