首发于CWIKIUS

Java 中如何将 String 转换为 Long

请考察下面的代码:

Long.parseLong("0", 10)        // returns 0L
 Long.parseLong("473", 10)      // returns 473L
 Long.parseLong("-0", 10)       // returns 0L
 Long.parseLong("-FF", 16)      // returns -255L
 Long.parseLong("1100110", 2)   // returns 102L
 Long.parseLong("99", 8)        // throws a NumberFormatException
 Long.parseLong("Hazelnut", 10) // throws a NumberFormatException
 Long.parseLong("Hazelnut", 36) // returns 1356099454469L

上面的代码是转换为 Long 的。

转换为 Float 也是一样的。

实际上,我们可能会用到下面的代码来转换。

NumberUtils.toLong("473");

NumberUtils 这个工具类是在

package org.apache.commons.lang3.math

包中的,同时主要也是为了避免出现 null 对象的转换异常。



根据官方的说法为:如果输入的字符串为 null 或者 0 的话,将会有下面的返回和输出。

NumberUtils.toLong(null) = 0L
         NumberUtils.toLong("")   = 0L
         NumberUtils.toLong("1")  = 1L

ossez.com/t/java-string

发布于 2022-01-06 23:43