BigDecimal and “java.lang.ArithmeticException: Non-terminating decimal expansion”

Pada beberapa kasus operasi pembagian pada tipe data java.math.BigDecimal bisa terjadi error seperti ini:

Exception in thread “main” java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

Berikut contoh kode program nya:

import java.math.BigDecimal;

/**
 * Test case for "java.lang.ArithmeticException:
 * Non-terminating decimal expansion" error with
 * BigDecimal.
 *
 * @author JM
 *
 */

public class TestBigDecimal {

    public static void main(String[] args) {

        String returnVal = TestBigDecimal.divide("1", "5");

        System.out.println("Test #1: returnVal = " + returnVal);

        returnVal = TestBigDecimal.divide("1", "2");

        System.out.println("Test #2: returnVal = " + returnVal);

        // Test(#3) will fail as the quotient (returnVal)
        // is a non-terminating decimal value.

        returnVal = TestBigDecimal.divide("1", "3");

        System.out.println("Test #3: returnVal = " + returnVal);
    }

    /**
     * Pembagian val1 dengan val2 mengembalikan nilai sebagai String.
     *
     * @param val1
     * @param val2
     * @return value as String
     */
    public static String divide(String val1, String val2) {

        BigDecimal v1 = new BigDecimal(val1);

        BigDecimal v2 = new BigDecimal(val2);

        return v1.divide(v2).toPlainString();

    }
}

Pada contoh diatas akan menghasilkan output:

Test #1: returnVal = 0.2
Test #2: returnVal = 0.5
Exception in thread “main” java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(Unknown Source)
at com.jm.client.TestBigDecimal.divide(TestBigDecimal.java:34)
at com.jm.client.TestBigDecimal.main(TestBigDecimal.java:20)

Untuk mengatasi masalah ini perlu dituliskan parameter tambahan pada methode divide, seperti misalnya presisi/ketelitian bilangan dan juga RoundingMode, seperti contoh berikut ini:


import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * Test case for "java.lang.ArithmeticException:
 * Non-terminating decimal expansion" error with
 * BigDecimal.
 *
 * @author JM
 *
 */
public class TestBigDecimal {

    public static void main(String[] args) {

        String returnVal = TestBigDecimal.divide("1", "5");

        System.out.println("Test #1: returnVal = " + returnVal);

        returnVal = TestBigDecimal.divide("1", "2");

        System.out.println("Test #2: returnVal = " + returnVal);

        // Test(#3) will now work as we have provided a scale
        // and a rounding mode to the divide() method

        returnVal = TestBigDecimal.divide("1", "3");

        System.out.println("Test #3: returnVal = " + returnVal);

    }

    /**
     * Pembagian val1 dengan val2 mengembalikan nilai sebagai String.
     *
     * @param val1
     * @param val2
     * @return value as String
     */
    public static String divide(String val1, String val2) {

        BigDecimal v1 = new BigDecimal(val1);

        BigDecimal v2 = new BigDecimal(val2);

        return v1.divide(v2, 2, RoundingMode.HALF_UP).toPlainString();

    }
} 

Outputnya kira-kira seperti ini:

Test #1: returnVal = 0.20
Test #2: returnVal = 0.50
Test #3: returnVal = 0.33

Sumber:

VB 6 Coding Style

In general, it’s more important to have some coding styles than to use a particular set of rules. Code that is consistent is easier to read, understand, debug, and maintain no matter what rules you use.

However, it amazes me how many developers seem to have no rules or rules that are inconsistent and contradictory. In one very large (56,000 line) project, I’ve seen people using arbitrary indentation, no comments, improper variable naming (for example, using an “m” prefix that normally means “module-level” for local variables), and so forth.

So here are the rules that I generally use. Adopt the ones that makes sense to you and replace the others. Note that these are the rules that I use for Visual Basic 6. I use slightly different rules for other languages, including VB .NET.

 

  • Indentation: Indent 4 spaces to show scope. Indent within a subroutine, loop, or If Then block as in the following:
        Private Sub MySub()
        Dim i As Integer
    
            For i = 1 To 10
                Debug.Print i
            Next i
        End Sub
  • Make sure indentation lines up block start and end statements. For example, make sure the If, Then, Else, and End If statements in a block all line up.
  • Declare variables at the beginning of a subroutine at the same level of indentation as the Sub statement. (A lot of people prefer indent the declarations. Whatever you prefer. Just pick one. Note that VB .NET indents them for you whether you like ot or not.)
  • Use Option Explicit and Option Strict.
  • Declare each variable on a separate line.
  • Prefix module-level variables with “m_” and use “Pascal Case” (capitalize the first letter of each word) as in m_NumEmployees.
  • Prefix global-level variables with “g_” and use “Pascal Case” as in g_NumEmployees.
  • Name constants in ALL CAPS with underscores as in MAX_EMPLOYEES.
  • Specify a data type for all variables and constants as in:
        Private Const MAX_EMPLOYEES As Long = 100
  • Name routine-local variables in lower case with underscores as in num_employees.
  • Use Pascal case for subroutine, function, property, and other routine names as in NumEmployees().
  • Always specify one of Private, Public, etc. whenever those are allowed. I.e. don’t declare a subroutine with just Sub, use Private or Public to make its scope obvious.
  • Use type prefixes on control names as in picEmployee (a PictureBox) and lblResult (a Label).
  • Do not use type prefixes (aka Hungarian notation) for other variables.
  • Make variable names obvious enough that you don’t miss Hungarian notation.
  • Use a comment at the beginning of every module explaining what its purpose is.
  • Use a comment before every routine explaining what the routine does. Explain parameters and return values.
  • Use liberal comments within the code to explain what it is doing.
  • Do not use GoTo.
  • Do not use IIF. It’s confusing and If Then Else is actually faster.
  • Do not use the : character to place more than one statement on a single line.
  • If a single-line If Then statement is long, make it a multi-line If Then End If statement so it’s easier to read.
  • Don’t try to make anything do too many things. For example, Visual Basic’s Line command draws lines or rectangles, optionally specifying the drawing color and whether the rectangle should be filled. This should have been at least two routines, Line and Rectangle.
  • When you use error handling code with an On Error GoTo statement, always place an Exit Sub statement immediately before the error handler. Never allow the code to drop into the error handling code. This makes the code run in a special error handling mode and can be quite confusing.
  • Use Debug.Assert to test for conditions that should not occur. This lets you catch bugs early and easily.
  • If you catch an error, check for all errors not just the ones you expect. Use Debug.Assert to catch those you don’t expect.
  • In a Select Case statement, use a Case Else to catch unexpected conditions. If you don’t think the condition should ever occur, use Debug.Assert to detect it.