01: /**********************************************************************
02: Copyright (c) 2002 Mike Martin (TJDO) and others. All rights reserved.
03: Licensed under the Apache License, Version 2.0 (the "License");
04: you may not use this file except in compliance with the License.
05: You may obtain a copy of the License at
06:
07: http://www.apache.org/licenses/LICENSE-2.0
08:
09: Unless required by applicable law or agreed to in writing, software
10: distributed under the License is distributed on an "AS IS" BASIS,
11: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: See the License for the specific language governing permissions and
13: limitations under the License.
14:
15:
16: Contributors:
17: 2002 Kelly Grizzle (TJDO)
18: 2003 Andy Jefferson - coding standards
19: ...
20: **********************************************************************/package org.jpox.util;
21:
22: import java.math.BigDecimal;
23:
24: /**
25: * Utility class providing SQL formatting methods.
26: *
27: * @version $Revision: 1.2 $
28: **/
29: public class SQLFormat {
30: /**
31: * Formats the given BigDecimal value into a SQL floating-point literal.
32: * BigDecimal.toString() is not well suited to this purpose because it never
33: * uses E-notation, which causes some values with large exponents to be
34: * output as long strings with tons of zeroes in them.
35: *
36: * @param bd The number to format.
37: *
38: * @return The formatted String.
39: */
40: public static String format(BigDecimal bd) {
41: String digits = bd.unscaledValue().abs().toString();
42: int scale = bd.scale();
43: int len = digits.length();
44:
45: /* Normalize by removing any trailing zeroes. */
46: while (len > 1 && digits.charAt(len - 1) == '0') {
47: --scale;
48: --len;
49: }
50:
51: if (len < digits.length()) {
52: digits = digits.substring(0, len);
53: }
54:
55: StringBuffer sb = new StringBuffer();
56:
57: if (bd.signum() < 0) {
58: sb.append('-');
59: }
60:
61: int exponent = len - scale;
62:
63: if (exponent < 0 || exponent > len) {
64: /* Output in E-notation. */
65: sb.append('.').append(digits).append('E').append(exponent);
66: } else if (exponent == len) {
67: /* Output as an integer. */
68: sb.append(digits);
69: } else {
70: /* Output as "intDigits.fracDigits". */
71: sb.append(digits.substring(0, exponent)).append('.')
72: .append(digits.substring(exponent));
73: }
74:
75: return sb.toString();
76: }
77: }
|