0

In searching for an answer, I used the solution provided in the following link : How to format a Java string with leading zero?

I have the following code that needs to be translated into java:

TRIM(TO_CHAR(123,'000X'))

From what I can tell, it translates the number into hexa and adds some leading zeros.

However, if I give a big value, I get ##### as answer, e.g. for the following code:

TRIM(TO_CHAR(999999,'000X'))

In Java, my current solution is the following:

String numberAsHex = Integer.toHexString(123);
System.out.println(("0000" + numberAsHex).substring(numberAsHex.length()));

It works fine for small numbers, but for big ones, like 999999 it outputs 423f. So it does the transformation, resulting the value f423f and then it cuts a part off. So I am nowhere near the value from Oracle

Any suggestion as to how to do this? Or why are ##### displayed in the Oracle case?

Teshte
  • 624
  • 1
  • 7
  • 26
  • Look at `SimpleNumberFormat` class. – talex Oct 02 '18 at 10:38
  • 1
    `TO_CHAR` outputs '#' characters when the format string is not large enough to accommodate the formatted output. `TO_CHAR(999999,'000X')` has to output five hex digits (F423F), but the format string only allows room for four characters. To indicate this condition `TO_CHAR` outputs four '#' characters instead of throwing an exception and abnormally terminating the program. – Bob Jarvis - Слава Україні Oct 02 '18 at 11:39

1 Answers1

1

Instead of Integer.toHexString I would recommend using String.format because of its greater flexibility.

int number = ...;
String numberAsHex = String.format("%06x", number);

The 06 means you get 6 digits with leading zeros, x means you get lowercase hexadecimal.

Examples:

  • for number = 123 you get numberAsHex = "00007b"
  • for number = 999999you get numberAsHex = "0f423f"
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49