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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4808715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:07:14  来源:igfitidea点击:

String to integer conversion in Java/JSP

javastringjsp

提问by RMa

I have a variable costdefined in a DB2 table as String. I'm getting it into a value object where it is defined as a Stringas 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 costas 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.

cost在 DB2 表中定义了一个变量String. 我将它放入一个值对象中,它也被定义为 a String。我需要检查来自 DB2 的值是否只是空格。如果只有空格,我需要将 0 移入其中。我还需要从中删除前导零。也许我所得到cost0000123。但是在 JSP 中我需要将它显示为123. 你是怎样做的?我将 vo 数据存储到会话变量中,并使用它在 JSP 中显示数据。

回答by Kevin Stembridge

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.

我会考虑更改您的数据库架构以将值存储在数字字段中。如果您不能这样做,请考虑更改值对象以将其存储为数字字段并解析您从数据库中检索到的字符串。

回答by jt.

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 Langto accomplish your task:

了解您所描述的大部分内容听起来像是极差的设计,您可以继续该路径并使用 scriptlet。以下示例使用Apache Commons Lang来完成您的任务:

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

回答by Adam

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.

如果你不能改变你的数据库。使用Integer.parseInt(javadoc)。(这是假设我们在这里处理整数,否则使用 中的等效项Double)。创建一个函数来处理您的字符串编号并在您的 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>