• 字符串转数字(with Java)


    1. 字符串中提取数字

    两个函数可以帮助我们从字符串中提取数字(整型、浮点型、字符型...)。

    • parseInt()、parseFloat()...
    • valueOf() 
      String str = "1230";
        int d = Integer.parseInt(str); //静态函数直接通过类名调用,返回int型
     //or
     int d3 = Integer.valueOf("1230"); //通过静态函数valueOf返回包装类Integer类型
     System.out.println("digit3: " + d3);

    注意:从字符串中提取可能会产生一种常见的异常: NumberFormatException。

    原因主要有两种:

    • Input string contains non-numeric characters. (比如含有字母"123aB")

    • Value out of range.(比如Byte.parseByte("128") byte的数值范围在 -128~127)

    解决方法:

      通过 try-catch-block 提前捕捉潜在异常。

     try {
                  float d2 = Float.parseFloat(str);
                  System.out.printf("digit2: %.2f ", d2 );
              } catch (NumberFormatException e){
                  System.out.println("Non-numerical string only.");
          }
      
    try {
                 byte d4 = Byte.parseByte(str);
                 System.out.println("digit3: " + d4);
             } catch (NumberFormatException e) {
                 System.out.println("
    Value out of range. It can not convert to digits.");
             }            

    2. 数字转字符串

    使用 String 类的 valueOf() 函数

     String s = String.valueOf(d); 

    3. 代码

    public class StringToDigit {
        public static void main(String[] args) {
    
            //convert string to digits using parseInt()、parseFloat()...
            String str = "127";
            int d = Integer.parseInt(str);
            System.out.printf("d: %d ", d);
    
            try {
                float d2 = Float.parseFloat(str);
                System.out.printf("digit2: %.2f ", d2 );
            } catch (NumberFormatException e){
                System.out.println("Non-numerical string only.");
            }
         
    
            //or using valueOf()
            int d3 = Integer.valueOf("1230");
            System.out.println("digit3: " + d3);
    
            try {
                byte d4 = Byte.parseByte(str);
                System.out.println("digit3: " + d4);
            } catch (NumberFormatException e) {
                System.out.println("
    Value out of range. It can not convert to digits.");
            }
    
            //convert digits to string using valueOf()
            System.out.println(String.valueOf(d));
            System.out.println(String.valueOf(d3));
        }
    }
    

      

     加油各位!如果觉得有用的话,可以点个推荐吗?(祈求脸.jpg) 

  • 相关阅读:
    ASP.NET页面事件执行过程 总结
    程序员最应该读的图书(中译版) [收藏]
    C# 中的委托和事件的详解资料
    已添加项。字典中的关键字
    TFS 删除团队项目集合
    注册后第一篇
    类型的权限已失败 SqlClientPermission
    C#创建Oracle存储过程
    使用MySQL with 递归查询菜单树
    MySQL 常用TSQL(持续更新...)
  • 原文地址:https://www.cnblogs.com/sheepcore/p/11601796.html
Copyright © 2020-2023  润新知