一般由字符串转换为数字会用到如下的代码
public static Number parse(String source)
{
if (source == null)
{
return null;
}
NumberFormat format = NumberFormat.getInstance();
try
{
return format.parse(source);
}
catch (ParseException e)
{
return null;
}
}
传入参数为"100.123",返回为数字100.123;
传入参数为"100.123a",返回结果仍然为100.123,假如有些情况需要严格验证输入数据必须为数字则需要用到下面的代码了:
public static Number parse(String source)
{
if (source == null)
{
return null;
}
NumberFormat format = NumberFormat.getInstance();
try
{
ParsePosition pos = new ParsePosition(0);
Number number = format.parse(source, pos);
boolean flag = pos.getIndex() == source.length() && pos.getErrorIndex() == -1;
return flag ? number : null;
}
catch (Exception e)
{
return null;
}
}
此时如果传入参数包含有非数字字符则返回null。
分享到:
相关推荐
在Spring框架中,配置文件是核心组件之一,它定义了bean的实例化、依赖注入以及其他的设置。当遇到“cvc-elt.1: 找不到元素 'beans' 的声明”这种异常时,通常意味着Spring在尝试解析XML配置文件时遇到了问题。...
Strict/permissive parsing JSONxx can parse JSON documents both in strict or permissive mode. When jsonxx::Settings::Parser is set to Strict, JSONxx parser will accept: Fully conformant JSON ...
The number of significant digits displayed in floating point numbers. ; http://php.net/precision precision = 14 ; Output buffering is a mechanism for controlling how much output data ; (excluding ...
PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:...
To make use of either more or less strict isolation levels in applications, locking can be customized for an entire session by setting the isolation level of the session with the SET TRANSACTION ...