Formats BigDecimal into a SQL floating-point literal : BigDecimal « Data Type « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Data Type » BigDecimalScreenshots 
Formats BigDecimal into a SQL floating-point literal
   
/**********************************************************************
Copyright (c) 2002 Mike Martin (TJDO) and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 

Contributors:
2002 Kelly Grizzle (TJDO)
2003 Andy Jefferson - coding standards
    ...
**********************************************************************/


import java.math.BigDecimal;

/**
 * Utility class providing SQL formatting methods.
 *
 @version $Revision: 1.2 $
 **/
public class SQLFormat
{
    /**
     * Formats the given BigDecimal value into a SQL floating-point literal.
     * BigDecimal.toString() is not well suited to this purpose because it never
     * uses E-notation, which causes some values with large exponents to be
     * output as long strings with tons of zeroes in them.
     *
     @param bd  The number to format.
     *
     @return  The formatted String.
     */
    public static String format(BigDecimal bd)
    {
        String digits = bd.unscaledValue().abs().toString();
        int scale = bd.scale();
        int len = digits.length();

        /* Normalize by removing any trailing zeroes. */
        while (len > && digits.charAt(len - 1== '0')
        {
            --scale;
            --len;
        }

        if (len < digits.length())
        {
            digits = digits.substring(0, len);
        }

        StringBuffer sb = new StringBuffer();

        if (bd.signum() 0)
        {
            sb.append('-');
        }

        int exponent = len - scale;

        if (exponent < || exponent > len)
        {
            /* Output in E-notation. */
            sb.append('.').append(digits).append('E').append(exponent);
        }
        else if (exponent == len)
        {
            /* Output as an integer. */
            sb.append(digits);
        }
        else
        {
            /* Output as "intDigits.fracDigits". */
            sb.append(digits.substring(0, exponent)).append('.').append(digits.substring(exponent));
        }

        return sb.toString();
    }
}
/////////////////////////////////////////
/*
 * The terms of the JPOX License are distributed with the software documentation.
 */

package org.jpox.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Random;

import org.jpox.util.SQLFormat;
import junit.framework.TestCase;


/**
 * Tests the functionality of {@link SQLFormat}.
 
 @author <a href="mailto:mmartin5@austin.rr.com">Mike Martin</a>
 
 */

public class SQLFormatTest extends TestCase
{
    /**
     * Used by the JUnit framework to construct tests.  Normally, programmers
     * would never explicitly use this constructor.
     *
     @param name   Name of the <tt>TestCase</tt>.
     */

    public SQLFormatTest(String name)
    {
        super(name);
    }


    private static final String[][] CUSTOM_CASES =
    {
        "0",          "0" },
        "12.34",      "12.34" },
        "1.234",      "1234e-3" },
        ".1234E12",   "123400000000" },
        "-.1234",     "-1234e-4" },
        "1234",       ".1234e+4" },
        ".75E10",     ".75e+10" },
        "-.75E10",    "-7.5e+9" },
        ".5E-9",      "5e-10" }
    };

    public void testCustomValues() throws Throwable
    {
        for (int i = 0; i < CUSTOM_CASES.length; ++i)
            assertEquals(CUSTOM_CASES[i][0], SQLFormat.format(new BigDecimal(CUSTOM_CASES[i][1])));
    }


    private static final int NUM_RANDOM_CASES = 5000;

    public void testRandomValues() throws Throwable
    {
        Random rnd = new Random(0L);

        for (int i = 0; i < NUM_RANDOM_CASES; ++i)
        {
            BigDecimal bd1 = new BigDecimal(new BigInteger(128, rnd), rnd.nextInt(100));
            String s = SQLFormat.format(bd1);
            BigDecimal bd2 = new BigDecimal(SQLFormat.format(bd1));

            assertEquals("Formatting " + bd1 + " yielded " + s + " which doesn't equal"0, bd1.compareTo(bd2));
        }
    }
}

   
    
    
  
Related examples in the same category
1. Round a double
2. Create Big Decimal Values via a long
3. Create a BigDecimal vis string
4. Multiply one BigDecimal to another BigDecimal
5. Subtract from one BigDecimal another BigDecimal
6. Divide one BigDecimal from another BigDecimal
7. Negate a BigDecimal
8. Setting the Decimal Place of a Big Decimal Value
9. Truncates the big decimal value
10. Do math operation for BigDecimal
11. Operate with big decimal values
12. Round a double by setting the scale
13. Create Big Decimal Values via a string
14. Calculation with BigDecimal
15. Parse BigDecimal
16. Value is rounded using the given method which is any method defined in BigDecimal
17. Round the given value to the specified number of decimal places. The value is rounded using the BigDecimal.ROUND_HALF_UP method.
18. Convert Object to BigDecimal
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.