`
justink
  • 浏览: 8759 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Strict Number Parsing

    博客分类:
  • Java
阅读更多
一般由字符串转换为数字会用到如下的代码
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配置文件解析失败报”cvc-elt.1: 找不到元素 ''beans'' 的声明”异常解决

    在Spring框架中,配置文件是核心组件之一,它定义了bean的实例化、依赖注入以及其他的设置。当遇到“cvc-elt.1: 找不到元素 'beans' 的声明”这种异常时,通常意味着Spring在尝试解析XML配置文件时遇到了问题。...

    A JSON parser in C++

    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 ...

    php.ini-development

    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 ...

    hls.min.js

    PARSING_INIT_SEGMENT:"hlsFragParsingInitSegment",FRAG_PARSING_USERDATA:"hlsFragParsingUserdata",FRAG_PARSING_METADATA:"hlsFragParsingMetadata",FRAG_PARSING_DATA:"hlsFragParsingData",FRAG_PARSED:...

    微软内部资料-SQL性能优化3

    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 ...

Global site tag (gtag.js) - Google Analytics