Any message handling application need to maintain an unique id for each message to track the status. We are generating ids in Oracle database, which are 24 chars long. As this is done with a sequence the id we get is having some zeros followed by a number like '000000001234567890123456'. To remove the leading zeros we are simply converting this to BigDecimal and then again back to string using DecimalFormat as shown in the below code. While doing this we realised that the max number that DecimalFormat can format successfully is 15 digits if all 9's else 16 digits. Any value beyond that is causing the number to be incremented as shown in the below output.
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.StringTokenizer;
public class Test
{
public static void main(String[] args)
{
String[] data = {"999999999999999", "9999999999999998", "9999999999999999", "18411028910519619"};
BigDecimal num = null;
DecimalFormat format = new DecimalFormat();
for(int i = 0;i < data.length; i++)
{
num = new BigDecimal(data[i]);
System.out.println("Bignum: " + num.toString() + " converted to: " + format.format(num));
}
}
}
Output with JDK 1.4:
Bignum: 999999999999999 converted to: 999,999,999,999,999
Bignum: 9999999999999998 converted to: 9,999,999,999,999,998
Bignum: 9999999999999999 converted to: 10,000,000,000,000,000
Bignum: 18411028910519619 converted to: 18,411,028,910,519,620
This is not an issue in JDK 1.6:
Bignum: 999999999999999 converted to: 999,999,999,999,999
Bignum: 9999999999999998 converted to: 9,999,999,999,999,998
Bignum: 9999999999999999 converted to: 9,999,999,999,999,999
Bignum: 18411028910519619 converted to: 18,411,028,910,519,619
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.StringTokenizer;
public class Test
{
public static void main(String[] args)
{
String[] data = {"999999999999999", "9999999999999998", "9999999999999999", "18411028910519619"};
BigDecimal num = null;
DecimalFormat format = new DecimalFormat();
for(int i = 0;i < data.length; i++)
{
num = new BigDecimal(data[i]);
System.out.println("Bignum: " + num.toString() + " converted to: " + format.format(num));
}
}
}
Output with JDK 1.4:
Bignum: 999999999999999 converted to: 999,999,999,999,999
Bignum: 9999999999999998 converted to: 9,999,999,999,999,998
Bignum: 9999999999999999 converted to: 10,000,000,000,000,000
Bignum: 18411028910519619 converted to: 18,411,028,910,519,620
This is not an issue in JDK 1.6:
Bignum: 999999999999999 converted to: 999,999,999,999,999
Bignum: 9999999999999998 converted to: 9,999,999,999,999,998
Bignum: 9999999999999999 converted to: 9,999,999,999,999,999
Bignum: 18411028910519619 converted to: 18,411,028,910,519,619
No comments:
Post a Comment