Link to home
Start Free TrialLog in
Avatar of wasabi3689
wasabi3689Flag for United States of America

asked on

how to format a number as ###,### in JSP/Java

How to format a number as ###,###

I have the following code


 <%
    DecimalFormat df = new DecimalFormat("###,###");
    long MySourceBytes = df.format((MyList.get(i).getSourceBytes())/1024);
 %>

Now I have the following error

An error occurred at line: 367 in the jsp file: /view2.jsp
Generated servlet error:
C:\Documents and Settings\ezchen\.netbeans\5.5\apache-tomcat-5.5.17_base\work\Catalina\localhost\NFD\org\apache\jsp\view2_jsp.java:644: incompatible types
found   : java.lang.String
required: long
            long MySourceBytes = df.format((MyList.get(i).getSourceBytes())/1024);
                                          ^

How to fix this problem?
Avatar of mrcoffee365
mrcoffee365
Flag of United States of America image

df.format returns a string.  Why do you format it if you are going to convert it to a long?

If you want to turn the string into a long, then something like
Long.parseLong( aString )
works.

You'll have to take the comma outfor parseLong -- you might want to use the DecimalFormat parse method to convert the string back to a number.
Try this:
 <%
    DecimalFormat df = new DecimalFormat("###,###");
    String MySourceBytes = df.format((MyList.get(i).getSourceBytes())/1024);
 %>
 ...
 I have <%=MySouceBytes%> Bytes!!
Avatar of wasabi3689

ASKER

MySourceBytes must be long from get function, now I need to convert MySourceBytes long into string value, then df it
or
can I directly format a long value output as "###,###"?
ASKER CERTIFIED SOLUTION
Avatar of bpmurray
bpmurray
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>can I directly format a long value output as "###,###"?

No -- long is a long, which is a binary type.  It doesn't have a string display format.  That's why there are classes like DecimalFormat, for formatting binary number types like long, when you want to display the value of a long variable in a String format.