KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > triactive > jdo > util > SQLFormat


1 /*
2  * Copyright 2002 (C) TJDO.
3  * All rights reserved.
4  *
5  * This software is distributed under the terms of the TJDO License version 1.0.
6  * See the terms of the TJDO License in the documentation provided with this software.
7  *
8  * $Id: SQLFormat.java,v 1.3 2004/01/25 22:31:38 jackknifebarber Exp $
9  */

10
11 package com.triactive.jdo.util;
12
13 import java.math.BigDecimal JavaDoc;
14
15
16 public class SQLFormat
17 {
18     /**
19      * Formats the given BigDecimal value into a SQL floating-point literal.
20      * BigDecimal.toString() is not well suited to this purpose because it never
21      * uses E-notation, which causes some values with large exponents to be
22      * output as long strings with tons of zeroes in them.
23      *
24      * @param bd The number to format.
25      *
26      * @return The formatted String.
27      */

28
29     public static String JavaDoc format(BigDecimal JavaDoc bd)
30     {
31         String JavaDoc digits = bd.unscaledValue().abs().toString();
32         int scale = bd.scale();
33         int len = digits.length();
34
35         /* Normalize by removing any trailing zeroes. */
36         while (len > 1 && digits.charAt(len - 1) == '0')
37         {
38             --scale;
39             --len;
40         }
41
42         if (len < digits.length())
43             digits = digits.substring(0, len);
44
45         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
46
47         if (bd.signum() < 0)
48             sb.append('-');
49
50         int exponent = len - scale;
51
52         if (exponent < 0 || exponent > len)
53         {
54             /* Output in E-notation. */
55             sb.append('.').append(digits).append('E').append(exponent);
56         }
57         else if (exponent == len)
58         {
59             /* Output as an integer. */
60             sb.append(digits);
61         }
62         else
63         {
64             /* Output as "intDigits.fracDigits". */
65             sb.append(digits.substring(0, exponent)).append('.').append(digits.substring(exponent));
66         }
67
68         return sb.toString();
69     }
70 }
71
Popular Tags