string转数字 java_字符串转数字(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("\nValue 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("\nValue 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)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值