## 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

 `8485868788899091929394` ```        } else if (clazz == Double.class) {             return (T) new Double(COUNTER.getAndIncrement());         } else if (clazz == Boolean.class) {             return (T) new Boolean(false);         } else if (clazz == BigDecimal.class) {             return (T) new BigDecimal(COUNTER.getAndIncrement());         } else if (clazz == BigInteger.class) {             return (T) new BigInteger("" + COUNTER.getAndIncrement());         } else if (clazz == java.sql.Date.class) {             return (T) new java.sql.Date(COUNTER.getAndIncrement());         } else if (clazz == java.sql.Time.class) { ```
View Full Code Here

 `247248249250251252253254255256257258` ```        assertTrue(rs.getBoolean(3));         assertTrue(rs.getBoolean("c"));         assertEquals(d.getTime(), rs.getDate(4).getTime());         assertEquals(d.getTime(), rs.getDate("d").getTime());         assertTrue(new BigDecimal("10.3").equals(rs.getBigDecimal(5)));         assertTrue(new BigDecimal("10.3").equals(rs.getBigDecimal("e")));         assertEquals(10.3, rs.getDouble(5));         assertEquals((float) 10.3, rs.getFloat(5));         assertTrue(Math.PI == rs.getDouble(6));         assertTrue(Math.PI == rs.getDouble("f")); ```
View Full Code Here

 `470471472473474475476477478479480` ```        Statement stat = conn.createStatement();         stat.execute("create table test(id int primary key, name varchar, amount decimal)");         PreparedStatement prep = conn.prepareStatement("insert into test values(?, ?, ?)");         prep.setInt(1, 1);         prep.setString(2, "Hello \\'Joe\n\\'");         prep.setBigDecimal(3, new BigDecimal("10.20"));         prep.executeUpdate();         stat.execute("create table test2(id int primary key,\n" +                 "a real, b double, c bigint,\n" +                 "d smallint, e boolean, f binary, g date, h time, i timestamp)", Statement.NO_GENERATED_KEYS);         prep = conn.prepareStatement("insert into test2 values(1, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); ```
View Full Code Here

 `781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846` ```            else if (Float.TYPE.equals(clazz))                 return number.floatValue();             else if (Float.class.equals(clazz))                 return new Float(number.floatValue());             else if (BigDecimal.class.equals(clazz))                 return new BigDecimal(number.doubleValue());             else if (BigInteger.class.equals(clazz))                 return new BigInteger(number.toString());            // else             // TODO log warn                       } else if (isDateTime(clazz)) {           return handleAsDate(clazz,value,customizeInfo,method);         } else if (clazz.isEnum()) {             String sValue = (value instanceof Map) ? ((String)((Map)value).get("_name")) : (String) value;             try{               return Enum.valueOf(clazz, sValue);             }catch(Throwable th){               // try in value fields               for(Object conzt: clazz.getEnumConstants()){             try{               // If xml value annotation use it.               if(clazz.getDeclaredField(((Enum)conzt).name()).                   getAnnotation(XmlEnumValue.class).value().equals(sValue)){                 return conzt;               }             }catch(Throwable t){};           }               // user error?               return null;             }         } else if (value instanceof String) {             String sValue = (String) value;             if(sValue.trim().isEmpty() && Number.class.isAssignableFrom(clazz)){               sValue = "0";               if(traceEnabled)traceLog.warn("Empty string passed for number. Converting it to zero. Field : " + method.getName());             }             if (String.class.equals(clazz))               return value;             else if (Boolean.TYPE.equals(clazz))                 return Boolean.parseBoolean(sValue);             else if (Boolean.class.equals(clazz))                 return Boolean.valueOf(sValue);             else if (Short.TYPE.equals(clazz)   || Short.class.equals(clazz))                 return Short.decode(sValue);             else if (Byte.TYPE.equals(clazz)   || Byte.class.equals(clazz))                 return Byte.decode(sValue);             else if (Integer.TYPE.equals(clazz) || Integer.class.equals(clazz))                 return Integer.decode(sValue);             else if (Long.TYPE.equals(clazz)  || Long.class.equals(clazz))                 return Long.decode(sValue);             else if (Float.TYPE.equals(clazz))                 return Float.parseFloat(sValue);             else if (Float.class.equals(clazz))                 return Float.valueOf(sValue);             else if (Double.TYPE.equals(clazz))                 return Double.parseDouble(sValue);             else if (Double.class.equals(clazz))                 return Double.valueOf(sValue);             else if (BigDecimal.class.equals(clazz))                 return new BigDecimal(sValue);             else if (BigInteger.class.equals(clazz))                 return new BigInteger(sValue);             else if (Character.TYPE.equals(clazz) || Character.class.equals(clazz)) {                 char charValue = 0;                 if (sValue.length() > 0) { ```
View Full Code Here

 `7374757677787980818283` ```        assertEquals(10, v.convertPrecision(10, false).getPrecision());         assertEquals(10, v.convertPrecision(10, false).getBytes().length);         assertEquals(32, v.convertPrecision(10, false).getBytes()[9]);         assertEquals(10, v.convertPrecision(10, true).getPrecision());         final Value vd = ValueDecimal.get(new BigDecimal("1234567890.123456789"));         assertEquals(19, vd.getPrecision());         assertEquals("1234567890.1234567", vd.convertPrecision(10, true).getString());         new AssertThrows(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1) { public void test() {             vd.convertPrecision(10, false);         }}; ```
View Full Code Here

 `235236237238239240241242243244245246247` ```        ValueDouble vd3 = vd1.modulus(vd2);         assertEquals(2, vd3.getDouble());     }     private void testModulusDecimal() {         final ValueDecimal vd1 = ValueDecimal.get(new BigDecimal(12));         new AssertThrows(ErrorCode.DIVISION_BY_ZERO_1) { public void test() {             vd1.modulus(ValueDecimal.get(new BigDecimal(0)));         }};         ValueDecimal vd2 = ValueDecimal.get(new BigDecimal(10));         ValueDecimal vd3 = vd1.modulus(vd2);         assertEquals(2, vd3.getDouble());     } ```
View Full Code Here

 `279280281282283284285` ```        }         buff.insert(len - scale, '.');         if (config.random().getBoolean(20)) {             buff.insert(0, '-');         }         return new BigDecimal(buff.toString());     } ```
View Full Code Here

 `150151152153154155156157158159160161162163164165166` ```        testValue(ValueDecimal.get(BigDecimal.ONE));         testValue(ValueDecimal.get(BigDecimal.TEN));         testValue(ValueDecimal.get(BigDecimal.ONE.negate()));         testValue(ValueDecimal.get(BigDecimal.TEN.negate()));         for (long i = 0; i >= 0; i += 10 + i / 4) {             testValue(ValueDecimal.get(new BigDecimal(i)));             testValue(ValueDecimal.get(new BigDecimal(-i)));             for (int j = 0; j < 200; j += 50) {                 testValue(ValueDecimal.get(new BigDecimal(i).setScale(j)));                 testValue(ValueDecimal.get(new BigDecimal(i * i).setScale(j)));             }             testValue(ValueDecimal.get(new BigDecimal(i * i)));         }         testValue(ValueDate.get(new Date(System.currentTimeMillis())));         testValue(ValueDate.get(new Date(0)));         testValue(ValueTime.get(new Time(System.currentTimeMillis())));         testValue(ValueTime.get(new Time(0))); ```
View Full Code Here

 `125126127128129130131132133134135` ```        }     }     private void testParseSpecialValue(String x) throws SQLException {         Object expected;         expected = new BigDecimal(x);         try {             expected = Long.decode(x);             expected = Integer.decode(x);         } catch (Exception e) {             // ignore ```
View Full Code Here

 `635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664` ```        stat.execute("INSERT INTO TEST VALUES(7,-99999998.99)");         stat.execute("INSERT INTO TEST VALUES(8,NULL)");         rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");         assertResultSetMeta(rs, 2, new String[] { "ID", "VALUE" }, new int[] { Types.INTEGER, Types.DECIMAL }, new int[] {                 10, 10 }, new int[] { 0, 2 });         BigDecimal bd;         rs.next();         assertTrue(rs.getInt(1) == 1);         assertTrue(!rs.wasNull());         assertTrue(rs.getInt(2) == -1);         assertTrue(!rs.wasNull());         bd = rs.getBigDecimal(2);         assertTrue(bd.compareTo(new BigDecimal("-1.00")) == 0);         assertTrue(!rs.wasNull());         o = rs.getObject(2);         trace(o.getClass().getName());         assertTrue(o instanceof BigDecimal);         assertTrue(((BigDecimal) o).compareTo(new BigDecimal("-1.00")) == 0);         rs.next();         assertTrue(rs.getInt(1) == 2);         assertTrue(!rs.wasNull());         assertTrue(rs.getInt(2) == 0);         assertTrue(!rs.wasNull());         bd = rs.getBigDecimal(2);         assertTrue(bd.compareTo(new BigDecimal("0.00")) == 0);         assertTrue(!rs.wasNull());         rs.next();         checkColumnBigDecimal(rs, 2, 1, "1.00");         rs.next();         checkColumnBigDecimal(rs, 2, 12345679, "12345678.89"); ```
View Full Code Here