Snippet IT IT News, Programming, Internet and Blogging

5Jan/100

Java: Format Integer Into Fixed Width String

Sometime, you may want to format an integer or a long value into a fixed width String. You need to display the value in fixed width especially in reports where you want to keep the numbers in aligned (e.g. 3456 as 0003456 and 1234 as 0001234).

Other than that, you may also want to format the integer value for a better visibility. For example, to display integer value as a document number (e.g. 12345678 as 00-01234-5678), for example an account number.

The Java.format() is not flexible enough to solve my problem. At least it cannot be used to format a fixed length document number in the format I want: XX-XXXX-XXXX. Therefore I decide write my own format function.

18Aug/090

Java: Format Long Integer Into Hexadecimal String

In software programming, sometime you may want to convert a long integer or integer into hexadecimal string for viewing purpose or also as a text format to be stored in text file or database.

The Java API itself does not have a class or function to convert a long into a fixed 16 characters hexadecimal string or an integer into  fixed 8 characters hexadecimal string.

The Java's Long.toHexString(long i) or Integer.toHexString(int i) only able to convert the integer value to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s and it does not support the reverse way (from hexadecimal string to long integer value).

20Mar/091

Java: Format integer into number of decimal places and performance

For certain reasons (e.g. precision issue), some programmer may store a float value (e.g. money) in integer variable. For example -12345678.90 is stored as -1234567890. To convert the integer value to number with number of decimal places is a problem.

There are several way to do it. You can simply use the Java's String.format(), DecimalFormat or Float.toString(). Most of them does not meet my requirements: Simple, fast, precise and with thousand separator. Therefore I wrote a simple class that ease myself.