简体   繁体   中英

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?

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);

Take into account that converting a decimal value into hex requires an exponent. You could get the hexadecimal String representing a numeric value using Formatter .

%A : The result is formatted as a hexadecimal floating-point number with a significand and an exponent
%X: The result is formatted as a hexadecimal integer

Use the %A conversion if you want to convert a decimal value:

System.out.println(String.format("%A", myBigDecimal));

Curiously, the code above is correct regarding the javadoc for Formatter , but there seems to be a related 9-year-old error in the javadocs, that has been fixed a few weeks ago in Java 8: 5035569 : (fmt) assertion error in Formatter for BigDecimal and %a . You can use the analog code below:

System.out.println(String.format("%A", myBigDecimal.doubleValue()));

EDIT
Judging by the value in your post, you don't really care about the fractional part. You could use the %X conversion in the pattern and just provide the BigInteger representation:

BigDecimal bd = new BigDecimal("18446744073709551616");
System.out.println(String.format("%X", bd.toBigInteger()));

Theoretically it is possible to represent BigDecimal as a hex string, simiolar to Double.toHexString

0x1.199999999999p+1

but AFAIK there is no standard way to do it and custom implementation will not be easy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM