【问题标题】:Convert String (timestamp) to integer将字符串(时间戳)转换为整数
【发布时间】:2014-02-13 15:49:09
【问题描述】:

我必须将字符串“1392298553937999872”转换为 int。该字符串是一个时间戳。通常这应该可以通过使用将其转换为 int:

Integer i = Integer.valueOf(1392298553937999872);

但我收到以下异常:

java.lang.NumberFormatException:对于输入字符串: "1392298553937999872"

如果我使用 double 它可以工作,但数字是错误的。那么如何将时间戳转换为 int 呢?

【问题讨论】:

    标签: java string integer


    【解决方案1】:

    将字符串转换为长字符串。

    String a="1392298553937999872";
    long b= Long.parseLong(a);
    

    【讨论】:

      【解决方案2】:

      数量大于Integer的最大值使用Long

      Long l = new Long("1392298553937999872");
      

      【讨论】:

        【解决方案3】:

        您尝试转换的数字超过了Integer.MAX_VALUE 值。你最好使用BigInteger

        BigInteger bigInteger = new BigInteger("1392298553937999872");
        

        【讨论】:

        • 为什么使用BigDecimal 表示整数? LongBigInteger 会更合适。
        【解决方案4】:

        您尝试转换的值大于Integer.MAX_VALUE (2,147,483,647),您应该使用LongBigInteger 的替代类型之一:

        Long bigValue = Long.parseLong("1392298553937999872");
        // ...
        Long bigValue = new Long("1392298553937999872");
        // ..
        Long bigValue = Long.valueOf("1392298553937999872");
        // ...
        BigInteger bigValue = new BigInteger("1392298553937999872");
        

        如果添加额外的库并且值可能会有所不同,您还可以使用 apache commons 的 NumberUtils。 NumberUtils.createNumber(String) 方法将根据提供的输入进行调整:

        Number bigValue = NumberUtils.createNumber(inputString);
        

        【讨论】:

          猜你喜欢
          • 2016-11-27
          • 2014-11-23
          • 2019-05-31
          • 2020-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-01
          • 1970-01-01
          相关资源
          最近更新 更多