Search code examples
numberformatexception

NumberFormatException in BigDecimal to int or long(java)



I am coding in Java,I want to transfer BigDecimal data to int or long, the data name is "recovered",its value is"889.0" and has the structure as follows:
[enter image description here][1]

I tried Long.valueOf(recovered.toString()) and Integer.valueOf(recovered.toString()),but both generate NumberFormatException.

I also tried recovered recovered.toString().getBytes() and I got: [enter image description here][2]

How can I have int or long value of "889.0"?
Thank you. [1]: https://i.sstatic.net/GF3tD.jpg [2]: https://i.sstatic.net/TXNBb.jpg


Solution

  • The string "889.0" is not a valid format to convert to a Long or an Integer, it is a decimal format and you could convert it to a Float or a Double.

    If you want an integer you could convert it to a float first and then use Float.intValue to convert it to an integer.

    Float f = Float.valueOf(recovered.toString();
    Integer i = f.intValue();