/** * Creates an aggregate of the passed long values * * @param values the longs to aggregate * @return An array of longs containing <b><code>AVG, MIN, MAX</code></b>. */ public static long[] aggregate(long... values) { if (values == null || values.length < 1) return new long[] {0, 0, 0}; long[] aggr = new long[3]; long max = Long.MIN_VALUE; long min = Long.MAX_VALUE; int cnt = 0; BigDecimal total = new BigDecimal(0); for (long value : values) { if (value == -1) continue; total = total.add(BigDecimal.valueOf(value)); if (value > max) max = value; if (value < min) min = value; cnt++; } try { aggr[0] = (cnt != 0 && total.longValue() > 0) ? (SimpleMath.avg(cnt, total.longValue())) : 0; } catch (Exception e) { System.err.println( "Failed to compute average for a total of [" + total + "] and count [" + cnt + "]. Stack trace follows:"); e.printStackTrace(System.err); } aggr[1] = min == Long.MAX_VALUE ? -1 : min; aggr[2] = max == Long.MIN_VALUE ? -1 : max; return aggr; }
/** {@inheritDoc} */ @Override protected boolean isDefault(BigDecimal boundValue) { if (boundValue != null) { if (isUsingLong()) { return boundValue.longValue() == Long.MAX_VALUE || boundValue.longValue() == Long.MIN_VALUE; } return boundValue.intValue() == Integer.MAX_VALUE || boundValue.intValue() == Integer.MIN_VALUE; } return super.isDefault(null); }
private RexNode makeCastExactToInterval(RelDataType toType, RexNode exp) { IntervalSqlType intervalType = (IntervalSqlType) toType; TimeUnit endUnit = intervalType.getIntervalQualifier().getEndUnit(); if (endUnit == null) { endUnit = intervalType.getIntervalQualifier().getStartUnit(); } int scale = 0; if (endUnit == TimeUnit.SECOND) { scale = Math.min( intervalType .getIntervalQualifier() .getFractionalSecondPrecision(typeFactory.getTypeSystem()), 3); } BigDecimal multiplier = BigDecimal.valueOf(endUnit.multiplier).divide(BigDecimal.TEN.pow(scale)); RelDataType decimalType = getTypeFactory() .createSqlType(SqlTypeName.DECIMAL, scale + intervalType.getPrecision(), scale); RexNode value = decodeIntervalOrDecimal(ensureType(decimalType, exp, true)); if (multiplier.longValue() != 1) { value = makeCall(SqlStdOperatorTable.MULTIPLY, value, makeExactLiteral(multiplier)); } return encodeIntervalOrDecimal(value, toType, false); }
public static long toLong(final BigDecimal number) { if (number == null) { return 0; } else { return number.longValue(); } }
/** * Converter from a numeric object to Long. Input is checked to be within range represented by * Long. */ static Long convertToLong(SessionInterface session, Object a) { if (a instanceof Integer) { return ValuePool.getLong(((Integer) a).intValue()); } else if (a instanceof Long) { return (Long) a; } else if (a instanceof BigDecimal) { BigDecimal bd = (BigDecimal) a; if (bd.compareTo(MAX_LONG) > 0 || bd.compareTo(MIN_LONG) < 0) { throw Error.error(ErrorCode.X_22003); } return ValuePool.getLong(bd.longValue()); } else if (a instanceof Double || a instanceof Float) { double d = ((Number) a).doubleValue(); if (session instanceof Session) { if (!((Session) session).database.sqlConvertTruncate) { d = java.lang.Math.rint(d); } } if (Double.isInfinite(d) || Double.isNaN(d) || d >= (double) Long.MAX_VALUE + 1 || d <= (double) Long.MIN_VALUE - 1) { throw Error.error(ErrorCode.X_22003); } return ValuePool.getLong((long) d); } else { throw Error.error(ErrorCode.X_42561); } }
@Override public long getCountFunctionBilled(Long spId, String start, String end) { StringBuilder sql = new StringBuilder(); sql.append("select count(distinct fs.card_no) from fee_stat fs") .append(" where fs.sp_id=") .append(spId) .append(" and fs.fee_type=") .append(FeeStat.TYPE_FUNCTION) .append(" and fs.operate_time>=TO_DATE('") .append(start) .append("','yyyymmdd')") .append(" and fs.operate_time<=TO_DATE('") .append(end) .append("','yyyymmdd')"); Session s = null; BigDecimal result = null; try { s = super.sessionFactory.openSession(); result = (BigDecimal) s.createSQLQuery(sql.toString()).uniqueResult(); } catch (Exception e) { e.printStackTrace(); } finally { try { s.close(); } catch (PlatformException he) { he.printStackTrace(); } } return result.longValue(); }
// If the Decision Table model was pre-5.4 Numeric data-types were always stored as // BigDecimals. This function attempts to set the correct DTCellValue property based // on the *true* data type. private void convertDTCellValueFromNumeric(DataType.DataTypes dataType, DTCellValue52 dcv) { // Generic type NUMERIC was always stored as a BigDecimal final BigDecimal value = (BigDecimal) dcv.getNumericValue(); switch (dataType) { case NUMERIC_BIGDECIMAL: dcv.setNumericValue(value == null ? null : value); break; case NUMERIC_BIGINTEGER: dcv.setNumericValue(value == null ? null : value.toBigInteger()); break; case NUMERIC_BYTE: dcv.setNumericValue(value == null ? null : value.byteValue()); break; case NUMERIC_DOUBLE: dcv.setNumericValue(value == null ? null : value.doubleValue()); break; case NUMERIC_FLOAT: dcv.setNumericValue(value == null ? null : value.floatValue()); break; case NUMERIC_INTEGER: dcv.setNumericValue(value == null ? null : value.intValue()); break; case NUMERIC_LONG: dcv.setNumericValue(value == null ? null : value.longValue()); break; case NUMERIC_SHORT: dcv.setNumericValue(value == null ? null : value.shortValue()); break; } }
/** * Converter from a numeric object to Long. Input is checked to be within range represented by * Long. */ static Long convertToLong(Object a) throws HsqlException { if (a instanceof Integer) { return ValuePool.getLong(((Integer) a).intValue()); } else if (a instanceof Long) { return (Long) a; } else if (a instanceof BigDecimal) { BigDecimal bd = (BigDecimal) a; if (bd.compareTo(MAX_LONG) > 0 || bd.compareTo(MIN_LONG) < 0) { throw Error.error(ErrorCode.X_22003); } return ValuePool.getLong(bd.longValue()); } else if (a instanceof Double || a instanceof Float) { double d = ((Number) a).doubleValue(); if (Double.isInfinite(d) || Double.isNaN(d) || d >= (double) Long.MAX_VALUE + 1 || d <= (double) Long.MIN_VALUE - 1) { throw Error.error(ErrorCode.X_22003); } return ValuePool.getLong((long) d); } else { throw Error.error(ErrorCode.X_42561); } }
private Object mapper(ResultSet rs, Class clz) throws Exception { Field[] fs = clz.getDeclaredFields(); Object obj = clz.newInstance(); for (Field f : fs) { String name = f.getName(); f.setAccessible(true); Class type = f.getType(); Object val = rs.getObject(name); if (val == null) { continue; } if (val instanceof BigDecimal) { BigDecimal tmp = (BigDecimal) val; if (type.getName().endsWith("Long")) { val = tmp.longValue(); } else if (type.getName().endsWith("Integer")) { val = tmp.intValue(); } else if (type.getName().endsWith("Short")) { val = tmp.shortValue(); } else if (type.getName().endsWith("Double")) { val = tmp.doubleValue(); } else { } } f.set(obj, val); } return obj; }
private PlacementInputQtyCorrectReponse validate( BigDecimal actualQty, BigDecimal inputQty, String targetType) throws PlacementQtyValidateException { placementQtyRequest.validateAfterCorrect(actualQty); PlacementInputQtyCorrectReponse response = new PlacementInputQtyCorrectReponse(); response.setPlacementQty(actualQty); boolean isQtyChanged = actualQty.compareTo(inputQty) < 0; boolean isAbsoluteQuantity = TargetTypeConsts.ABSOLUTE_QUANTITY.equals(targetType); if (isQtyChanged && isAbsoluteQuantity) { response.setMessage("委托数量超过了指令未委托数量,将替换为【" + actualQty.longValue() + "】"); } else if (isQtyChanged && isAbsoluteQuantity == false) { response.setMessage("委托金额超过了指令未委托金额,将替换为【" + actualQty.longValue() + "】"); } else { response.setMessage(""); } return response; }
public static Long getNextMobileId_direccion(Long mobile_id, Long id_vendedor) { Session session = HibernateUtil.currentSession(); SQLQuery query = (SQLQuery) session .createSQLQuery( "SELECT MAX(MOBILE_ID_DIRECCION) FROM CLIENTES_DIRECCIONES " + "WHERE MOBILE_ID = :mobile_id AND ID_VENDEDOR = :id_vendedor") .setParameter("mobile_id", mobile_id) .setParameter("id_vendedor", id_vendedor) .setCacheable(false); BigDecimal result = (BigDecimal) query.uniqueResult(); return result == null || result.longValue() < com.vincomobile.Constants.FIRST_MOBILE_ID_DIRECCION ? com.vincomobile.Constants.FIRST_MOBILE_ID_DIRECCION : result.longValue() + 1; }
/** * Converts a day count into year, month and day components. Algorithm is derived from J R * Stockton (http://www.merlyn.demon.co.uk/daycount.htm). * * @param days day count * @return result array */ private static long[] ymd(final BigDecimal days) { BigDecimal d = days; BigDecimal t = d.add(BD36525).multiply(BD4).divideToIntegralValue(BD146097).subtract(BigDecimal.ONE); BigDecimal y = BD100.multiply(t); d = d.subtract(BD36524.multiply(t).add(t.divideToIntegralValue(BD4))); t = d.add(BD366).multiply(BD4).divideToIntegralValue(BD1461).subtract(BigDecimal.ONE); y = y.add(t); d = d.subtract(BD365.multiply(t).add(t.divideToIntegralValue(BD4))); final BigDecimal m = BD5.multiply(d).add(BD2).divideToIntegralValue(BD153); d = d.subtract(BD153.multiply(m).add(BD2).divideToIntegralValue(BD5)); long mm = m.longValue(); if (mm > 9) { mm -= 12; y = y.add(BigDecimal.ONE); } return new long[] {y.subtract(BigDecimal.valueOf(ADD_NEG)).longValue(), mm + 2, d.longValue()}; }
@SuppressWarnings("unchecked") public static <T> T cast(Object obj, Class<T> clazz) throws Exception { if (obj == null) { return null; } TypeToken<T> type = TypeToken.of(clazz).wrap(); TypeToken<?> objType = TypeToken.of(obj.getClass()).wrap(); if (type.isAssignableFrom(objType)) { return (T) obj; } if (TypeToken.of(List.class).isAssignableFrom(type) && objType.isArray()) { List<Object> list = Arrays.asList((Object[]) obj); return (T) list; } if (type.isArray() && TypeToken.of(List.class).isAssignableFrom(objType)) { List<?> list = (List<?>) obj; TypeToken<?> componentType = type.getComponentType(); Class<?> rawType; if (componentType == null) { rawType = Object.class; } else { rawType = componentType.getRawType(); } Object[] array = (Object[]) Array.newInstance(rawType, list.size()); return (T) list.toArray(array); } if (clazz.isEnum()) { return (T) Enum.valueOf((Class<? extends Enum>) clazz, obj.toString()); } if (TypeToken.of(String.class).isAssignableFrom(type)) { return (T) obj.toString(); } if (TypeToken.of(Number.class).isAssignableFrom(type)) { BigDecimal num = new BigDecimal(obj.toString()); if (TypeToken.of(Integer.class).isAssignableFrom(type)) { return (T) Integer.valueOf(num.intValue()); } if (TypeToken.of(Long.class).isAssignableFrom(type)) { return (T) Long.valueOf(num.longValue()); } if (TypeToken.of(Short.class).isAssignableFrom(type)) { return (T) Short.valueOf(num.shortValue()); } if (TypeToken.of(Byte.class).isAssignableFrom(type)) { return (T) Byte.valueOf(num.byteValue()); } if (TypeToken.of(Float.class).isAssignableFrom(type)) { return (T) Float.valueOf(num.floatValue()); } if (TypeToken.of(Double.class).isAssignableFrom(type)) { return (T) Double.valueOf(num.doubleValue()); } } return null; }
public long getLong() throws SQLException { truncated_ = 0; outOfBounds_ = false; if (value_.compareTo(LONG_MAX_VALUE) > 0 || value_.compareTo(LONG_MIN_VALUE) < 0) { // we don't count the fractional part of the number as truncation int length = value_.toBigInteger().toByteArray().length; truncated_ = length - 8; outOfBounds_ = true; } return value_.longValue(); }
@OnClick(R.id.displayItemsBtn) public void showItems() { // create some dummy items to display in second screen List<OrderItem> items = new ArrayList<OrderItem>(); OrderItem item1 = new OrderItem(); // these are the only required fields for second screen display item1.setName("Item1"); item1.setUnitPrice(100l); item1.setQuantity(1.0f); items.add(item1); OrderItem item2 = new OrderItem(); // these are the only required fields for second screen display item2.setName("Item2"); item2.setUnitPrice(100l); item2.setQuantity(1.0f); // item2.setDiscount(-50l); List<Discount> discounts = new ArrayList<>(); Discount discount = new Discount(); discount.setAmount(-50l); discount.setId(UUID.randomUUID().toString()); discount.setCustomName("My custom discount"); discounts.add(discount); item2.setDiscounts(discounts); items.add(item2); OrderItem item3 = new OrderItem(); // these are the only required fields for second screen display item3.setName("Item3"); item3.setUnitPrice(100l); item3.setQuantity(2.0f); items.add(item3); try { if (secondScreenService != null) { BigDecimal total = new BigDecimal(0); for (OrderItem item : items) { BigDecimal price = new BigDecimal(item.getUnitPrice()); price.setScale(2, RoundingMode.HALF_UP); price = price.multiply(new BigDecimal(item.getQuantity())); total = total.add(price); } secondScreenService.showItem(items, total.longValue(), "USD"); } } catch (RemoteException e) { e.printStackTrace(); } }
@Override public void setBigDecimal(BigDecimal value) throws SQLException { if (value == null) { setNull(); return; } // check if value is within bounds if (value.compareTo(BD_MAX_LONG) > 0 || value.compareTo(BD_MIN_LONG) < 0) throw new TypeConversionException(LONG_CONVERSION_ERROR + " " + value); setLong(value.longValue()); }
public static Long getMobileId_direccion( Session session, Long mobile_id_cliente, Long mobile_id_direccion, Long mobile_id) { SQLQuery query = (SQLQuery) session .createSQLQuery( "SELECT ID_DIRECCION FROM CLIENTES_DIRECCIONES WHERE MOBILE_ID_CLIENTE = :mobile_id_cliente AND MOBILE_ID_DIRECCION = :mobile_id_direccion AND MOBILE_ID = :mobile_id") .setParameter("mobile_id_cliente", mobile_id_cliente) .setParameter("mobile_id_direccion", mobile_id_direccion) .setParameter("mobile_id", mobile_id) .setCacheable(false); BigDecimal result = (BigDecimal) query.uniqueResult(); return result == null ? 0L : result.longValue(); }
// 18. purpose: getLong with Defined Decimal Property public void testGetLongConversionFromDefinedDecimalProperty() { // dataObject's type add int property property_c = new SDOProperty(aHelperContext); property_c.setName(PROPERTY_NAME_C); property_c.setType(SDOConstants.SDO_DECIMAL); type_c.addDeclaredProperty(property_c); dataObject_c._setType(type_c); long db = 12; BigDecimal bd = new BigDecimal(db); dataObject_a.setBigDecimal(propertyPath_a_b_c, bd); // add it to instance list this.assertEquals(bd.longValue(), dataObject_a.getLong(propertyPath_a_b_c)); }
public static final long objectToLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); try { if (o == null) return -1L; else { BigDecimal bigDecimal = new BigDecimal(o.toString()); bigDecimal.intValue(); return bigDecimal.longValue(); } } catch (NumberFormatException e) { e.printStackTrace(); return -1L; } }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((client == null) ? 0 : client.hashCode()); result = prime * result + ((fromCurr == null) ? 0 : fromCurr.hashCode()); result = prime * result + id; result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((toCurr == null) ? 0 : toCurr.hashCode()); long temp; temp = toCurrAmount.longValue(); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; }
public long[] getRange(int shard) { BigDecimal start = new BigDecimal(limit) .multiply(new BigDecimal(shard + 1)) .add(new BigDecimal(offset)) .subtract(new BigDecimal(limit)); if (start.longValue() == 0) { start = new BigDecimal(1); } else { start = start.add(new BigDecimal(1)); } BigDecimal stop = new BigDecimal(limit).multiply(new BigDecimal(shard + 1)).add(new BigDecimal(offset)); if (stop.longValue() > end) { stop = new BigDecimal(end); } if (ordinalOffset == true) { start = start.subtract(new BigDecimal(1)); stop = stop.subtract(new BigDecimal(1)); } long[] r = {start.longValue(), stop.intValue()}; return r; }
protected Object toRetunType(BigDecimal result) { if (_expressionClass.isAssignableFrom(Boolean.class)) { return decodeBoolean(result); } else if (_expressionClass.isAssignableFrom(Double.class)) { return result.doubleValue(); } else if (_expressionClass.isAssignableFrom(Float.class)) { return result.floatValue(); } else if (_expressionClass.isAssignableFrom(Integer.class)) { return result.intValue(); } else if (_expressionClass.isAssignableFrom(Long.class)) { return result.longValue(); } else { return decodeString(result); } }
public void testRoundExactIntegralDoubleToLong() { for (double d : INTEGRAL_DOUBLE_CANDIDATES) { // every mode except UNNECESSARY BigDecimal expected = new BigDecimal(d).setScale(0, UNNECESSARY); boolean isInBounds = expected.compareTo(MAX_LONG_AS_BIG_DECIMAL) <= 0 & expected.compareTo(MIN_LONG_AS_BIG_DECIMAL) >= 0; try { assertEquals(expected.longValue(), DoubleMath.roundToLong(d, UNNECESSARY)); assertTrue(isInBounds); } catch (ArithmeticException e) { assertFalse(isInBounds); } } }
private static ArrayList<Long> primesUnder(long n) { long check = 3; ArrayList<Long> result = new ArrayList<Long>(); result.add((long) 2); while (check <= n) { BigDecimal ctr = new BigDecimal(Long.toString(check)); if (factors(ctr).size() == 2) { System.out.println("I'm adding " + ctr + " to the ArrayList."); result.add(ctr.longValue()); } check += 2; } return result; }
public void testRoundFractionalDoubleToLong() { for (double d : FRACTIONAL_DOUBLE_CANDIDATES) { for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) { BigDecimal expected = new BigDecimal(d).setScale(0, mode); boolean isInBounds = expected.compareTo(MAX_LONG_AS_BIG_DECIMAL) <= 0 & expected.compareTo(MIN_LONG_AS_BIG_DECIMAL) >= 0; try { assertEquals(expected.longValue(), DoubleMath.roundToLong(d, mode)); assertTrue(isInBounds); } catch (ArithmeticException e) { assertFalse(isInBounds); } } } }
@SuppressWarnings("unchecked") public static Long getExpressValue(Map map, String expressionStr) throws ParseException { Long expValue = 0L; map = instanlExpressMap(map); if (!StringUtils.isNullObject(expressionStr)) { JexlEngine jexl = JexlManager.getJexlEngine(); Expression expression = jexl.createExpression(expressionStr); JexlContext jexlContext = new MapContext(map); Object obj = (Object) expression.evaluate(jexlContext); if (null != obj) { BigDecimal b = new BigDecimal(obj.toString()); b = b.setScale(0, BigDecimal.ROUND_HALF_UP); expValue = b.longValue(); } } return expValue; }
public static String convert(final BigDecimal decimal) { BigDecimal temp = decimal.setScale(2, MathConstants.roundingMode); StringBuilder val = new StringBuilder(convert(temp.longValue())); if (val.charAt(val.length() - 1) != ' ') { val.append(' '); } val.setCharAt(0, Character.toUpperCase(val.charAt(0))); String t = temp.toPlainString(); int index = t.indexOf('.'); val.append("and "); if (index >= 0) { return val + t.substring(index + 1) + "/100"; } return val + "00/100"; }
@Transactional public void addBabysitterAdvice( String countyGuid, ServiceOrder order, Map<String, Date> expectedDate) { // 添加需要通知的月嫂 // CountyLevel countyLevel = dao.getResultByGUID(CountyLevel.class, // countyLevelGuid); String hql = "from Babysitter b where b.county.guid=? and b.level.level.money>=? and b.state = 1 "; List<Babysitter> babysitters = dao.getListResultByHQL(Babysitter.class, hql, countyGuid, order.getOrderPrice()); // 添加可以抢单月嫂策略,SQL已经判断了所属城市、级别、审核状态三个条件 // 1.排除最低薪水不符合条件的 List<Babysitter> removeBabysitters = new ArrayList<Babysitter>(); if (babysitters.size() == 0) return; BigDecimal salary = new BigDecimal(order.getOrderPrice()); salary = salary.add(new BigDecimal(-1000)); double rate = 1; if (order.getRate() != 0) rate = order.getRate(); salary = salary.multiply(new BigDecimal(rate)); long salaryLong = salary.longValue(); for (Babysitter babysitter : babysitters) { if (babysitter.getLowerSalary() > salaryLong) removeBabysitters.add(babysitter); } babysitters.removeAll(removeBabysitters); // 2.排除档期不符合条件 if (babysitters.size() == 0) return; if (removeBabysitters.size() != 0) removeBabysitters.clear(); for (Babysitter babysitter : babysitters) { if (!ExpectedDateCreate.checkBabysitterOrder(babysitter, expectedDate)) { removeBabysitters.add(babysitter); } } babysitters.removeAll(removeBabysitters); // 添加月嫂通知 if (babysitters.size() == 0) return; for (Babysitter babysitter : babysitters) { PanicBuyingBabysitterAdvice advice = PanicBuyingBabysitterAdvice.getInstance(); advice.setBabysitter(babysitter); advice.setServiceOrder(order); advice.setIsAdvice(false); advice.setIsOver(false); dao.add(advice); } }
/** * Adds the specified dayTime duration. * * @param add value to be added */ private void add(final BigDecimal add) { // normalized modulo: sc % 60 vs. (-sc + sc % 60 + 60 + sc) % 60 final BigDecimal sc = sec().add(add); sec = sc.signum() >= 0 ? sc.remainder(BD60) : sc.negate().add(sc.remainder(BD60)).add(BD60).add(sc).remainder(BD60); final long mn = Math.max(min(), 0) + div(sc.longValue(), 60); min = (byte) mod(mn, 60); final long ho = Math.max(hou, 0) + div(mn, 60); hou = (byte) mod(ho, 24); final long da = div(ho, 24); final long[] ymd = ymd(days().add(BigDecimal.valueOf(da))); yea = ymd[0]; mon = (byte) ymd[1]; day = (byte) ymd[2]; }
private Object handlePrimitive(JsonPrimitive json) { if (json.isBoolean()) return json.getAsBoolean(); else if (json.isString()) return json.getAsString(); else { BigDecimal bigDec = json.getAsBigDecimal(); // Find out if it is an int type try { bigDec.toBigIntegerExact(); try { return bigDec.intValueExact(); } catch (ArithmeticException e) { } return bigDec.longValue(); } catch (ArithmeticException e) { } // Just return it as a double return bigDec.doubleValue(); } }