简体   繁体   English

Java / JSP中的字符串到整数的转换

[英]String to integer conversion in Java/JSP

I have a variable cost defined in a DB2 table as String . 我有一个可变的cost在DB2表定义的String I'm getting it into a value object where it is defined as a String as well. 我将其放入一个值对象中,该对象也被定义为String I need to check if the value coming in from DB2 is only spaces. 我需要检查来自DB2的值是否仅是空格。 If it is only spaces, I need to move 0 into it. 如果只有空格,则需要将0移入其中。 I also need to remove leading zeros from it. 我还需要从中删除前导零。 I may get cost as 0000123 . 我可能会得到0000123 cost But in JSP I need to display it as 123 . 但是在JSP中,我需要将其显示为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. 我将vo数据存储到会话变量中,并使用它在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: 以下示例使用Apache Commons Lang完成您的任务:

<%= 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) . 使用Integer.parseInt (javadoc) (This is assuming we are dealing with integers here, otherwise use the equivalent in Double ). (这是假设我们在这里处理整数,否则在Double使用等效项)。 Create a function to process your String number and use it in your JSP. 创建一个函数来处理您的String数字并在您的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM