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

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.

Masalah ieframe.dll

Pada saat kita menggunakan control internet control pada VB6 tidak 100% berjalan mulus. Ketika komputer diinstall browser dengan IE versi >IE6 maka akan menemui pesan error berikut “File Not found ‘C:\Windows\system32\ieframe.dll\1′” Solusi nya adalah dengan mencari registry dengan kata kunci ‘C:\Windows\system32\ieframe.dll\1′, dengan menggunakan tool seperti tuneUp 2009, dan mengganti text ‘C:\Windows\system32\ieframe.dll\1′ menjadi ‘C:\Windows\system32\ieframe.dll’

Automate Excel via VB

Cara membuat file excel melalui VB 6.0:

Private Sub Command1_Click()
    On Error GoTo errH
    Dim oExcel As Object
    Dim oWB As Object
    Dim oWS As Object
    Dim oRng As Object

    Set oExcel = CreateObject("Excel.Application")

    Set oWB = oExcel.Workbooks.Add
    Set oWS = oWB.Worksheets("Sheet1")
    Set oRng = oWS.Range("A1")
    oRng.Value = "Hello World"

    'oWS.Cells(1, 1).Value
    oWB.SaveAs ("c:\Hello World.xls")
    oWB.Close

    GoTo Cleanup
errH:
    If Err.Number = 9 Then 'jika error pada pembukaan worksheet
        MsgBox "Tidak dapat membuka worksheet, mungkin nama worksheet salah", vbCritical, "Error"
    Else
        MsgBox Err.Description, vbCritical, "Error"
    End If
Cleanup:
    Set oWS = Nothing
    On Error Resume Next
    If Not oWB Is Nothing Then oWB.Close
    Set oWB = Nothing
    oExcel.Quit
    Set oExcel = Nothing
    On Error GoTo 0
End Sub

jQuery Styling Alternate Rows

Membuat tampilan table menjadi alternate row berikut cara nya:
Misalkan ada file html:

<table>
  <tr>
    <td>As You Like It</td>
    <td>Comedy</td>
    <td></td>
  </tr>
  <tr>
    <td>All's Well that Ends Well</td>
    <td>Comedy</td>
    <td>1601</td>
  </tr>
  <tr>
    <td>Hamlet</td>
    <td>Tragedy</td>
    <td>1604</td>
  </tr>
  <tr>
    <td>Macbeth</td>
    <td>Tragedy</td>
    <td>1606</td>
  </tr>
  <tr>
    <td>Romeo and Juliet</td>
    <td>Tragedy</td>
    <td>1595</td>
  </tr>
  <tr>
    <td>Henry IV, Part I</td>
    <td>History</td>
    <td>1596</td>
  </tr>
  <tr>
    <td>Henry V</td>
    <td>History</td>
    <td>1599</td>
  </tr>
</table>

file css:

tr {
  background-color: #fff;
}
.alt {
  background-color: #ccc;
}

file js:

$(document).ready(function() {
  $('tr:odd').addClass('alt');
});

tampilan:

jQuery

Spring Framework 2

Melanjutkan pembahasan yang lalu, untuk class-class yang digunakan pada tutorial kali ini sama dengan tutorial sebelumnya, hanya saja disini akan ada sedikit perubahan dan penambahan file yaitu pada implementasi Class dalam hal ini kita tambah satu file lagi yaitu: CalculateSpring.java

package com.arulsoft.springtutorial;  

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class CalculateSpring {

    private Operation ops;
    private ResultWriter wtr;

    public void setOps(Operation ops) {
        this.ops = ops;
    }

    public void setWriter(ResultWriter writer) {
        this.wtr = writer;
    }

    public static void main(String[] args) {
        BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
        CalculateSpring calc = (CalculateSpring) factory.getBean("opsbean");
        calc.execute(args);
    }

    public void execute(String[] args) {
        long op1 = Long.parseLong(args[0]);
        long op2 = Long.parseLong(args[1]);
        wtr.showResult("The result of " + op1 + ops.getOpsName() + op2 + " is " + ops.operate(op1, op2) + "!");
    }
}

Kemudian kita buat file xml configurasi untuk spring framework:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="screen" class="com.arulsoft.springtutorial.ScreenWriter" />
    <bean id="multiply" class="com.arulsoft.springtutorial.OpMultiply" />
    <bean id="add" class="com.arulsoft.springtutorial.OpAdd" />
    <bean id="opsbean" class="com.arulsoft.springtutorial.CalculateSpring">
        <property name="ops" ref="multiply" />
        <property name="writer" ref="screen"/>
    </bean>
</beans>

Nah selesai deh, tinggal di-running, oh iya jangan lupa menambahkan library spring frameworknya. Sementara ini dulu untuk kelanjutannya tunggu postingan berikutnya…. :D

Spring Framework Tutorial

bagi yang ingin belajar spring framework, ni ada situs yang sangat membantu untuk pemula seperti saya, http://www.javapassion.com/handsonlabs/springhelloworld/, disitu dicontohkan bagaimana membuat program helloworld sederhana yang dimodifikasi sedemikian rupa sehingga dapat disesuaikan dengan kebutuhan. Penjelasan rincinya ada disini.

Spring Framework Tutorial 1

Tutorial berikut adalah hasil dari belajar Spring Framework pada buku Beginning Spring Framework 2
Beginning Spring Framework 2

Konsep dari spring framework adalah bagaimana membuat aplikasi dalam bentuk komponen yang dapat disusun menjadi aplikasi yang utuh. Proses ini disebut sebagai wiring. Hal ini dapat dianalogikan seperti komponen alat listrik. Baca selebihnya »

Disable Pop Up menu From Textbox

A common Frequently Asked Question is how to disable the popup menu of a TextBox. Since VB5 was released it’s possible to use the AdressOf keyword to add a Hook and a callback function. Just add this code to a .BAS module and call the Hook sub and pass the hWnd of a textbox as an argument. You must call the UnHook sub before you unload the form or you might get a General Protection

pertanyaan yang sering ditanyakan adalah bagaimana men-disable menu popup yang ada pada Textbox, berikut ini adalah contoh program kecil untuk men-disable menu popup tersebut:

buat kode berikut pada deklarasi modul:

Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" _
    (ByVal lpPrevWndFunc As Long, _
    ByVal hWnd As Long, _
    ByVal Msg As Long, _
    ByVal wParam As Long, _
    ByVal lParam As Long) As Long

Declare Function SetWindowLong Lib "user32" _
    Alias "SetWindowLongA" _
    (ByVal hWnd As Long, _
    ByVal nIndex As Long, _
    ByVal dwNewLong As Long) As Long

Public Const GWL_WNDPROC = -4
Public Const WM_RBUTTONUP = &H205
Public lpPrevWndProc As Long
Private lngHWnd As Long

Buat kode berikut pada modul:

Public Sub Hook(hWnd As Long)
    lngHWnd = hWnd
    lpPrevWndProc = SetWindowLong(lngHWnd, GWL_WNDPROC, _
    AddressOf WindowProc)
End Sub

Public Sub UnHook()
    Dim lngReturnValue As Long
    lngReturnValue = SetWindowLong(lngHWnd, GWL_WNDPROC, lpPrevWndProc)
End Sub

Function WindowProc(ByVal hw As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Select Case uMsg
        Case WM_RBUTTONUP
            'Do nothing
            'Or popup you own menu
        Case Else
            WindowProc = CallWindowProc(lpPrevWndProc, hw, uMsg, wParam, lParam)
    End Select
End Function

Buat kode berikut, letakkan pada event Form_Load() dimana Textbox berada:

Call Hook(Text1.hWnd)

Setting SmartGWT

Untuk setting smartGwt pada eclipse ikuti langkah berikut:

1. download and install Eclipse 3.4 (Ganymede)
2. Download GWT 1.6 Plugin feat SDK
3. Extract, Add SmartGWT to project
Untuk lebih jelasnya bisa ikuti video tutorial berikut:

Part 1:

Part 2: