开发者

String to integer conversion in Java/JSP

I have a variable cost defined in a DB2 table as String. I'm ge开发者_StackOverflowtting it into a value object where it is defined as a String as well. I need to check if the value coming in from DB2 is only spaces. If it is only spaces, I need to move 0 into it. I also need to remove leading zeros from it. I may get cost as 0000123. But in JSP I need to display it as 123. How do you do that? I'm storing the vo data into a session variable and using this, I'm displaying the data in JSP.


I would consider changing your database schema to store the value in a numeric field. If you can't do that, consider changing the value object to store it as a numeric field and parse the string you retrieve from the database.


Understanding that most of what you have described sounds like extremely poor design, you can continue the path and use a scriptlet. The following example uses Apache Commons Lang to accomplish your task:

<%= org.apache.commons.lang.math.NumberUtils.toInt(org.apache.commons.lang.StringUtils.trimToNull(cost),0) %>


If you can't change your database. Use Integer.parseInt (javadoc). (This is assuming we are dealing with integers here, otherwise use the equivalent in Double). Create a function to process your String number and use it in your JSP.

<%
function String processNumber(String value){
  if(value == null || value.trim().length() == 0){
     value = "0"//use a zero if all we have is whitespace or if the value is null
  }

  int intValue = 0;//store the integer version (which won't have leading zeros)
  try{
    int intValue = Integer.parseInt(value);//process the number
  }
  catch(Exception e){
    intValue = 0;//use 0 if there's a problem
  }
  return "" + intValue;//return the String version free of leading zeros
}
%>
<p>Number: <%= processNumber(getValue()) //replace getValue with however you get your value %></p>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜