01: /*
02: * Copyright 2002 (C) TJDO.
03: * All rights reserved.
04: *
05: * This software is distributed under the terms of the TJDO License version 1.0.
06: * See the terms of the TJDO License in the documentation provided with this software.
07: *
08: * $Id: SQLFormat.java,v 1.3 2004/01/25 22:31:38 jackknifebarber Exp $
09: */
10:
11: package com.triactive.jdo.util;
12:
13: import java.math.BigDecimal;
14:
15: public class SQLFormat {
16: /**
17: * Formats the given BigDecimal value into a SQL floating-point literal.
18: * BigDecimal.toString() is not well suited to this purpose because it never
19: * uses E-notation, which causes some values with large exponents to be
20: * output as long strings with tons of zeroes in them.
21: *
22: * @param bd The number to format.
23: *
24: * @return The formatted String.
25: */
26:
27: public static String format(BigDecimal bd) {
28: String digits = bd.unscaledValue().abs().toString();
29: int scale = bd.scale();
30: int len = digits.length();
31:
32: /* Normalize by removing any trailing zeroes. */
33: while (len > 1 && digits.charAt(len - 1) == '0') {
34: --scale;
35: --len;
36: }
37:
38: if (len < digits.length())
39: digits = digits.substring(0, len);
40:
41: StringBuffer sb = new StringBuffer();
42:
43: if (bd.signum() < 0)
44: sb.append('-');
45:
46: int exponent = len - scale;
47:
48: if (exponent < 0 || exponent > len) {
49: /* Output in E-notation. */
50: sb.append('.').append(digits).append('E').append(exponent);
51: } else if (exponent == len) {
52: /* Output as an integer. */
53: sb.append(digits);
54: } else {
55: /* Output as "intDigits.fracDigits". */
56: sb.append(digits.substring(0, exponent)).append('.')
57: .append(digits.substring(exponent));
58: }
59:
60: return sb.toString();
61: }
62: }
|