2011-01-26 71 views
0

我有一个变量cost,在DB2表中定义为String。我将它放到一个值对象中,它也被定义为String。我需要检查从DB2进来的值是否只有空格。如果只有空格,我需要将0移入它。我也需要删除它的前导零。我可能会得到cost作为0000123。但在JSP中,我需要将其显示为123。你是怎样做的?我将vo数据存储到会话变量中,并使用它,我在JSP中显示数据。在Java/JSP中将字符串转换为整数

+1

你问这个问题[几个](http://stackoverflow.com/questions/4797034/how-to-remove-leading-zeros-from- a-session-variable-in-jsp)[times](http://stackoverflow.com/questions/4786966/how-to-trim-leading-zeros-before-displaying-the-field-in-jsp)之前,与不同的帐户。请不要再次提出同样的问题。如果答案不能以某种方式让你满意,请澄清通过编辑/改进问题或在答案上发表评论。 – BalusC 2011-01-26 19:07:43

回答

2

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

+0

事实上,从根本上解决问题(修复数据库中的数据类型),之后不要进行破解/解决。 – BalusC 2011-01-26 19:07:06

0

如果你不能改变你的数据库。使用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> 
1

了解,大部分你所描述听起来像设计极其恶劣的东西,你可以继续路径和使用小脚本。下面的示例使用Apache Commons Lang来完成你的任务:

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