Search code examples
javahexbigdecimal

How to convert only the integer part of a BigDecimal to hex string?


I have a number of type BigDecimal, for example 18446744073709551616, and I want to convert it to hexadecimal value. I'm fine with truncating the fractional portion.

Is there a way to do this instead of doing it manually?


Solution

  • Judging by your example you should use BigInteger instead of BigDecimal. This way you could use

    new BigInteger("18446744073709551616").toString(16)
    

    If you can't change type of original object convert it to BigInteger later in method

    new BigDecimal("18446744073709551616").toBigInteger().toString(16);