## Examples of java.math.BigDecimal

• java.math.BigDecimal
ger=19, scale=2}
but
{@code 21/110 = 0.190 // integer=190, scale=3}

Note that for add, subtract, and multiply, the reduction in scale will equal the number of digit positions of the exact result which are discarded. If the rounding causes a carry propagation to create a new high-order digit position, an additional digit of the result is discarded than when no new digit position is created.

Other methods may have slightly different rounding semantics. For example, the result of the {@code pow} method using the{@linkplain #pow(int,MathContext) specified algorithm} canoccasionally differ from the rounded mathematical result by more than one unit in the last place, one {@linkplain #ulp() ulp}.

Two types of operations are provided for manipulating the scale of a {@code BigDecimal}: scaling/rounding operations and decimal point motion operations. Scaling/rounding operations ( {@link #setScale setScale} and {@link #round round}) return a {@code BigDecimal} whose value is approximately (or exactly) equalto that of the operand, but whose scale or precision is the specified value; that is, they increase or decrease the precision of the stored number with minimal effect on its value. Decimal point motion operations ( {@link #movePointLeft movePointLeft} and{@link #movePointRight movePointRight}) return a {@code BigDecimal} created from the operand by moving the decimalpoint a specified distance in the specified direction.

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of {@code BigDecimal} methods. Thepseudo-code expression {@code (i + j)} is shorthand for "a{@code BigDecimal} whose value is that of the {@code BigDecimal}{@code i} added to that of the {@code BigDecimal}{@code j}." The pseudo-code expression {@code (i == j)} isshorthand for " {@code true} if and only if the{@code BigDecimal} {@code i} represents the same value as the{@code BigDecimal} {@code j}." Other pseudo-code expressions are interpreted similarly. Square brackets are used to represent the particular {@code BigInteger} and scale pair defining a{@code BigDecimal} value; for example [19, 2] is the{@code BigDecimal} numerically equal to 0.19 having a scale of 2.

Note: care should be exercised if {@code BigDecimal} objectsare used as keys in a {@link java.util.SortedMap SortedMap} orelements in a {@link java.util.SortedSet SortedSet} since{@code BigDecimal}'s natural ordering is inconsistent with equals. See {@link Comparable}, {@link java.util.SortedMap} or {@link java.util.SortedSet} for moreinformation.

All methods and constructors for this class throw {@code NullPointerException} when passed a {@code null} objectreference for any input parameter. @see BigInteger @see MathContext @see RoundingMode @see java.util.SortedMap @see java.util.SortedSet @author Josh Bloch @author Mike Cowlishaw @author Joseph D. Darcy

 `540541542543544545546547548549550551` ```    private void testRow(Statement stat, String name) throws SQLException {         ResultSet rs = stat.executeQuery("SELECT * FROM " + name + " WHERE ID=1");         rs.next();         assertEquals("Hello", rs.getString("NAME"));         assertEquals(-1, rs.getByte("XT"));         BigDecimal bd = rs.getBigDecimal("XD");         assertTrue(bd.equals(new BigDecimal("10.30")));         Timestamp ts = rs.getTimestamp("XTS");         String s = ts.toString();         assertEquals("2001-02-03 11:22:33.4455", s);         assertTrue(ts.equals(Timestamp.valueOf("2001-02-03 11:22:33.4455")));         assertEquals(new byte[] { (byte) 255, (byte) 1, (byte) 2 }, rs.getBytes("XBY")); ```
View Full Code Here

 `106107108109110111112113114115116` ```    private static List[] sampleBatch(int rows) {         List[] batch = new List[rows];                 for (int i = 0; i < rows; i++) {             long currentTime = System.currentTimeMillis();             Object[] data = { new BigDecimal("" + i), //\$NON-NLS-1\$                               new BigInteger(Integer.toString(i)),                               (i%2 == 0) ? Boolean.FALSE: Boolean.TRUE,                               new Byte((byte)i),                               new Character((char)i),                               new Date(currentTime), ```
View Full Code Here

 `132133134135136137138139140141142` ```        List[] batch = new List[rows];                 for (int i = 0; i < rows; i++) {             long currentTime = System.currentTimeMillis();             int mod = i%14;             Object[] data = { (mod == 0) ? null : new BigDecimal("" + i), //\$NON-NLS-1\$                               (mod == 1) ? null : new BigInteger(Integer.toString(i)),                               (mod == 2) ? null : ((i%2 == 0) ? Boolean.FALSE: Boolean.TRUE),                               (mod == 3) ? null : new Byte((byte)i),                               (mod == 4) ? null : new Character((char)i),                               (mod == 5) ? null : new Date(currentTime), ```
View Full Code Here

 `336337338339340341342343344345346` ```        assertEquals("INTEGER", meta.getColumnTypeName(1));     }     private void testArray(Connection conn) throws SQLException {         PreparedStatement prep = conn.prepareStatement("select * from table(x int = ?) order by x");         prep.setObject(1, new Object[] { new BigDecimal("1"), "2" });         ResultSet rs = prep.executeQuery();         rs.next();         assertEquals("1", rs.getString(1));         rs.next();         assertEquals("2", rs.getString(1)); ```
View Full Code Here

 `779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812` ```        stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");         PreparedStatement prep = conn                 .prepareStatement("SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM TEST");         prep.setObject(1, new Boolean(true));         prep.setObject(2, "Abc");         prep.setObject(3, new BigDecimal("10.2"));         prep.setObject(4, new Byte((byte) 0xff));         prep.setObject(5, new Short(Short.MAX_VALUE));         prep.setObject(6, new Integer(Integer.MIN_VALUE));         prep.setObject(7, new Long(Long.MAX_VALUE));         prep.setObject(8, new Float(Float.MAX_VALUE));         prep.setObject(9, new Double(Double.MAX_VALUE));         prep.setObject(10, java.sql.Date.valueOf("2001-02-03"));         prep.setObject(11, java.sql.Time.valueOf("04:05:06"));         prep.setObject(12, java.sql.Timestamp.valueOf("2001-02-03 04:05:06.123456789"));         prep.setObject(13, new java.util.Date(java.sql.Date.valueOf("2001-02-03").getTime()));         prep.setObject(14, new byte[] { 10, 20, 30 });         prep.setObject(15, new Character('a'), Types.OTHER);         prep.setObject(16, "2001-01-02", Types.DATE);         // converting to null seems strange...         prep.setObject(17, "2001-01-02", Types.NULL);         prep.setObject(18, "3.725", Types.DOUBLE);         prep.setObject(19, "23:22:21", Types.TIME);         prep.setObject(20, new java.math.BigInteger("12345"), Types.OTHER);         rs = prep.executeQuery();         rs.next();         assertTrue(rs.getObject(1).equals(new Boolean(true)));         assertTrue(rs.getObject(2).equals("Abc"));         assertTrue(rs.getObject(3).equals(new BigDecimal("10.2")));         assertTrue(rs.getObject(4).equals((byte) 0xff));         assertTrue(rs.getObject(5).equals(new Short(Short.MAX_VALUE)));         assertTrue(rs.getObject(6).equals(new Integer(Integer.MIN_VALUE)));         assertTrue(rs.getObject(7).equals(new Long(Long.MAX_VALUE)));         assertTrue(rs.getObject(8).equals(new Float(Float.MAX_VALUE))); ```
View Full Code Here

 `156157158159160161162` ```     * @param value the value      * @param scale the scale      * @return the big decimal object      */     BigDecimal getBigDecimal(int value, int scale) {         return new BigDecimal(new BigInteger(String.valueOf(value)), scale);     } ```
View Full Code Here

 `127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222` ```        prep.setInt(1, dId);         prep.setInt(2, warehouseId);         rs = db.query(prep);         rs.next();         int oId = rs.getInt(1) - 1;         BigDecimal tax = rs.getBigDecimal(2);         rs.close();         prep = prepare("SELECT C_DISCOUNT, C_LAST, C_CREDIT, W_TAX "                 + "FROM CUSTOMER, WAREHOUSE "                 + "WHERE C_ID=? AND W_ID=? AND C_W_ID=W_ID AND C_D_ID=?");         prep.setInt(1, cId);         prep.setInt(2, warehouseId);         prep.setInt(3, dId);         rs = db.query(prep);         rs.next();         BigDecimal discount = rs.getBigDecimal(1);         // c_last         rs.getString(2);         // c_credit         rs.getString(3);         BigDecimal wTax = rs.getBigDecimal(4);         rs.close();         BigDecimal total = new BigDecimal("0");         for (int number = 1; number <= olCnt; number++) {             int olId = itemId[number - 1];             int olSupplyId = supplyId[number - 1];             int olQuantity = quantity[number - 1];             prep = prepare("SELECT I_PRICE, I_NAME, I_DATA "                     + "FROM ITEM WHERE I_ID=?");             prep.setInt(1, olId);             rs = db.query(prep);             if (!rs.next()) {                 if (rollback) {                     // item not found - correct behavior                     db.rollback();                     return;                 }                 throw new SQLException("item not found: " + olId + " "                         + olSupplyId);             }             BigDecimal price = rs.getBigDecimal(1);             // i_name             rs.getString(2);             String data = rs.getString(3);             rs.close();             prep = prepare("SELECT S_QUANTITY, S_DATA, "                     + "S_DIST_01, S_DIST_02, S_DIST_03, S_DIST_04, S_DIST_05, "                     + "S_DIST_06, S_DIST_07, S_DIST_08, S_DIST_09, S_DIST_10 "                     + "FROM STOCK WHERE S_I_ID=? AND S_W_ID=?");             prep.setInt(1, olId);             prep.setInt(2, olSupplyId);             rs = db.query(prep);             if (!rs.next()) {                 if (rollback) {                     // item not found - correct behavior                     db.rollback();                     return;                 }                 throw new SQLException("item not found: " + olId + " "                         + olSupplyId);             }             int sQuantity = rs.getInt(1);             String sData = rs.getString(2);             String[] dist = new String[10];             for (int i = 0; i < 10; i++) {                 dist[i] = rs.getString(3 + i);             }             rs.close();             String distInfo = dist[dId - 1];             stock[number - 1] = sQuantity;             if ((data.indexOf("original") != -1)                     && (sData.indexOf("original") != -1)) {                 bg[number - 1] = 'B';             } else {                 bg[number - 1] = 'G';             }             if (sQuantity > olQuantity) {                 sQuantity = sQuantity - olQuantity;             } else {                 sQuantity = sQuantity - olQuantity + 91;             }             prep = prepare("UPDATE STOCK SET S_QUANTITY=? "                     + "WHERE S_W_ID=? AND S_I_ID=?");             prep.setInt(1, sQuantity);             prep.setInt(2, olSupplyId);             prep.setInt(3, olId);             db.update(prep, "updateStock");             BigDecimal olAmount = new BigDecimal(olQuantity).multiply(                     price).multiply(ONE.add(wTax).add(tax)).multiply(                     ONE.subtract(discount));             olAmount = olAmount.setScale(2, BigDecimal.ROUND_HALF_UP);             amt[number - 1] = olAmount;             total = total.add(olAmount);             prep = prepare("INSERT INTO ORDER_LINE (OL_O_ID, OL_D_ID, OL_W_ID, OL_NUMBER, "                     + "OL_I_ID, OL_SUPPLY_W_ID, "                     + "OL_QUANTITY, OL_AMOUNT, OL_DIST_INFO) " ```
View Full Code Here

 `273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433` ```        } else {             byName = false;             last = "";             cId = random.getNonUniform(1023, 1, bench.customersPerDistrict);         }         BigDecimal amount = random.getBigDecimal(random.getInt(100, 500000),                 2);         Timestamp datetime = new Timestamp(System.currentTimeMillis());         PreparedStatement prep;         ResultSet rs;         prep = prepare("UPDATE DISTRICT SET D_YTD = D_YTD+? "                 + "WHERE D_ID=? AND D_W_ID=?");         prep.setBigDecimal(1, amount);         prep.setInt(2, dId);         prep.setInt(3, warehouseId);         db.update(prep, "updateDistrict");         prep = prepare("UPDATE WAREHOUSE SET W_YTD=W_YTD+? WHERE W_ID=?");         prep.setBigDecimal(1, amount);         prep.setInt(2, warehouseId);         db.update(prep, "updateWarehouse");         prep = prepare("SELECT W_STREET_1, W_STREET_2, W_CITY, W_STATE, W_ZIP, W_NAME "                 + "FROM WAREHOUSE WHERE W_ID=?");         prep.setInt(1, warehouseId);         rs = db.query(prep);         rs.next();         // w_street_1         rs.getString(1);         // w_street_2         rs.getString(2);         // w_city         rs.getString(3);         // w_state         rs.getString(4);         // w_zip         rs.getString(5);         String wName = rs.getString(6);         rs.close();         prep = prepare("SELECT D_STREET_1, D_STREET_2, D_CITY, D_STATE, D_ZIP, D_NAME "                 + "FROM DISTRICT WHERE D_ID=? AND D_W_ID=?");         prep.setInt(1, dId);         prep.setInt(2, warehouseId);         rs = db.query(prep);         rs.next();         // d_street_1         rs.getString(1);         // d_street_2         rs.getString(2);         // d_city         rs.getString(3);         // d_state         rs.getString(4);         // d_zip         rs.getString(5);         String dName = rs.getString(6);         rs.close();         BigDecimal balance;         String credit;         if (byName) {             prep = prepare("SELECT COUNT(C_ID) FROM CUSTOMER "                     + "WHERE C_LAST=? AND C_D_ID=? AND C_W_ID=?");             prep.setString(1, last);             prep.setInt(2, cdId);             prep.setInt(3, wId);             rs = db.query(prep);             rs.next();             int namecnt = rs.getInt(1);             rs.close();             if (namecnt == 0) {                 // TODO TPC-C: check if this can happen                 db.rollback();                 return;             }             prep = prepare("SELECT C_FIRST, C_MIDDLE, C_ID, "                     + "C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, "                     + "C_PHONE, C_CREDIT, C_CREDIT_LIM, "                     + "C_DISCOUNT, C_BALANCE, C_SINCE FROM CUSTOMER "                     + "WHERE C_LAST=? AND C_D_ID=? AND C_W_ID=? "                     + "ORDER BY C_FIRST");             prep.setString(1, last);             prep.setInt(2, cdId);             prep.setInt(3, wId);             rs = db.query(prep);             // locate midpoint customer             if (namecnt % 2 != 0) {                 namecnt++;             }             for (int n = 0; n < namecnt / 2; n++) {                 rs.next();             }             // c_first             rs.getString(1);             // c_middle             rs.getString(2);             cId = rs.getInt(3);             // c_street_1             rs.getString(4);             // c_street_2             rs.getString(5);             // c_city             rs.getString(6);             // c_state             rs.getString(7);             // c_zip             rs.getString(8);             // c_phone             rs.getString(9);             credit = rs.getString(10);             // c_credit_lim             rs.getString(11);             // c_discount             rs.getBigDecimal(12);             balance = rs.getBigDecimal(13);             // c_since             rs.getTimestamp(14);             rs.close();         } else {             prep = prepare("SELECT C_FIRST, C_MIDDLE, C_LAST, "                     + "C_STREET_1, C_STREET_2, C_CITY, C_STATE, C_ZIP, "                     + "C_PHONE, C_CREDIT, C_CREDIT_LIM, "                     + "C_DISCOUNT, C_BALANCE, C_SINCE FROM CUSTOMER "                     + "WHERE C_ID=? AND C_D_ID=? AND C_W_ID=?");             prep.setInt(1, cId);             prep.setInt(2, cdId);             prep.setInt(3, wId);             rs = db.query(prep);             rs.next();             // c_first             rs.getString(1);             // c_middle             rs.getString(2);             // c_last             rs.getString(3);             // c_street_1             rs.getString(4);             // c_street_2             rs.getString(5);             // c_city             rs.getString(6);             // c_state             rs.getString(7);             // c_zip             rs.getString(8);             // c_phone             rs.getString(9);             credit = rs.getString(10);             // c_credit_lim             rs.getString(11);             // c_discount             rs.getBigDecimal(12);             balance = rs.getBigDecimal(13);             // c_since             rs.getTimestamp(14);             rs.close();         }         balance = balance.add(amount);         if (credit.equals("BC")) {             prep = prepare("SELECT C_DATA INTO FROM CUSTOMER "                     + "WHERE C_ID=? AND C_D_ID=? AND C_W_ID=?");             prep.setInt(1, cId);             prep.setInt(2, cdId); ```
View Full Code Here

 `657658659660661662663664665666667` ```                prep.setInt(1, noId);                 prep.setInt(2, dId);                 prep.setInt(3, warehouseId);                 rs = db.query(prep);                 rs.next();                 BigDecimal amount = rs.getBigDecimal(1);                 rs.close();                 prep = prepare("UPDATE CUSTOMER SET C_BALANCE=C_BALANCE+? "                         + "WHERE C_ID=? AND C_D_ID=? AND C_W_ID=?");                 prep.setBigDecimal(1, amount);                 prep.setInt(2, noId); ```
View Full Code Here

 `3435363738394041424344` ```    static ComplexObject build(Integer id, boolean isNull) {         ComplexObject obj = new ComplexObject();         obj.id = id;         obj.amount = isNull ? null : Long.valueOf(1);         obj.name = isNull ? null : "hello";         obj.value = isNull ? null : new BigDecimal("1");         obj.birthday = isNull ? null : java.sql.Date.valueOf("2001-01-01");         obj.time = isNull ? null : Time.valueOf("10:20:30");         obj.created = isNull ? null : Timestamp.valueOf("2002-02-02 02:02:02");         return obj;     } ```
View Full Code Here