示例#1
14
 /** Constructs a new BigFraction from the given BigDecimal object. */
 public BigFraction(BigDecimal d) {
   this(
       d.scale() < 0
           ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()))
           : d.unscaledValue(),
       d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale()));
 }
示例#2
0
 public static long getTimeFromSpeedAndDistance(
     final BigDecimal speedInMPH, final BigDecimal distanceInMiles) {
   final double speed = speedInMPH.doubleValue();
   final double distance = distanceInMiles.doubleValue();
   final double result = (distance * 3600000.0d) / speed;
   return Math.round(result);
 }
  /** {@inheritDoc} */
  @Override
  public Move determineNextMove(Player currentPlayer, Player otherPlayer) {

    int ttl =
        Math.min(
            this.historyCount,
            Math.min(currentPlayer.getNumberOfRounds(), otherPlayer.getNumberOfRounds()));
    double p;

    if (ttl == 0) p = this.thresholdWon;
    else {
      int won = 0;
      for (int i = 0; i < ttl; i++) {
        BigDecimal curGin = currentPlayer.getRound(-i - 1).getGain();
        BigDecimal othGin = otherPlayer.getRound(-i - 1).getGain();
        if (curGin.doubleValue() / curGin.add(othGin).doubleValue() > this.thresholdWon) won++;
      }

      p = (double) won / ttl > this.thresholdWon ? this.probabilityWon : this.probabilityLost;
      //		if (currentPlayer.getNumberOfRounds() > 0 && currentPlayer.getRound(- 1).getMove() !=
      // Move.COOPERATE)
      //			p = 1 - p;
    }

    return random.nextDouble() < p ? Move.COOPERATE : Move.DECEIVE;
  }
 private void calculateTotal() {
   BigDecimal total = BigDecimal.ZERO;
   for (PenjualanDetail d : penjualanDetails) {
     total = total.add(d.getSubTotal());
   }
   txtTotal.setText(TextComponentUtils.formatNumber(total));
 }
 /**
  * Convert 4 bytes binary angle to float
  *
  * @param ang four bytes binary angle
  * @return float value of angle with precision of two decimal in degrees
  */
 static float calcAngle(int ang) {
   final double maxval = 4294967296.0;
   double temp = (ang / maxval) * 360.0;
   BigDecimal bd = new BigDecimal(temp);
   BigDecimal result = bd.setScale(3, RoundingMode.HALF_DOWN);
   return result.floatValue();
 }
  // tret Integer, Float and BigDecimal
  public Object operateWithNumbers(Object previousValue, Object currentValue) {
    logger.debug("IN");
    Object resultToReturn = null;

    if (currentValue instanceof Integer) {
      Integer currVal = (Integer) currentValue;
      Integer prevVal = (Integer) previousValue;
      Integer result = currVal + prevVal;
      resultToReturn = result;
    } else if (currentValue instanceof Float) {
      Float currVal = (Float) currentValue;
      Float prevVal = (Float) previousValue;
      Float result = currVal + prevVal;
      resultToReturn = result;
    } else if (currentValue instanceof BigDecimal) {
      BigDecimal currVal = (BigDecimal) currentValue;
      BigDecimal prevVal = (BigDecimal) previousValue;
      BigDecimal result = prevVal.add(currVal);
      resultToReturn = result;
    } else {
      logger.error("Error in measure type: trying to sum a value that is not a number");
      return null;
    }

    logger.debug("OUT");
    return resultToReturn;
  }
示例#7
0
 private String stringValue(Double valueIndex) {
   String recordOut = "";
   BigDecimal bdValue = new BigDecimal(valueIndex).setScale(3, RoundingMode.HALF_EVEN);
   switch (bdValue.intValue()) {
     case 1:
       recordOut = "Monday (1)";
       break;
     case 2:
       recordOut = "Tuesday (2)";
       break;
     case 3:
       recordOut = "Wednesday (3)";
       break;
     case 4:
       recordOut = "Thursday (4)";
       break;
     case 5:
       recordOut = "Friday (5)";
       break;
     case 6:
       recordOut = "Saturday (6)";
       break;
     case 0:
       recordOut = "Sunday (7)";
       break;
   }
   return recordOut;
 }
  public static void assertEquals(
      final String message,
      final BigDecimal expected,
      final BigDecimal actual,
      final BigDecimal delta) {
    if (expected == actual) {
      return;
    }

    if (expected.compareTo(actual) == 0) {
      return;
    }

    final BigDecimal deltaActual = expected.subtract(actual).abs();
    if (deltaActual.compareTo(delta) <= 0) {
      return;
    }

    Assert.fail(
        (message == null ? "" : message)
            + "\nExpected=<"
            + expected
            + ">"
            + "\nActual=<"
            + actual
            + ">"
            + "\nDelta=<"
            + delta
            + ">");
  }
示例#9
0
 /**
  * Parse a String size to Bytes.
  *
  * @param spaceSize the size of a space, e.g. 10GB, 5TB, 1024
  * @return the space size in bytes
  */
 public static long parseSpaceSize(String spaceSize) {
   double alpha = 0.0001;
   String ori = spaceSize;
   String end = "";
   int tIndex = spaceSize.length() - 1;
   while (tIndex >= 0) {
     if (spaceSize.charAt(tIndex) > '9' || spaceSize.charAt(tIndex) < '0') {
       end = spaceSize.charAt(tIndex) + end;
     } else {
       break;
     }
     tIndex--;
   }
   spaceSize = spaceSize.substring(0, tIndex + 1);
   double ret = Double.parseDouble(spaceSize);
   end = end.toLowerCase();
   if (end.isEmpty() || end.equals("b")) {
     return (long) (ret + alpha);
   } else if (end.equals("kb")) {
     return (long) (ret * Constants.KB + alpha);
   } else if (end.equals("mb")) {
     return (long) (ret * Constants.MB + alpha);
   } else if (end.equals("gb")) {
     return (long) (ret * Constants.GB + alpha);
   } else if (end.equals("tb")) {
     return (long) (ret * Constants.TB + alpha);
   } else if (end.equals("pb")) {
     // When parsing petabyte values, we can't multiply with doubles and longs, since that will
     // lose presicion with such high numbers. Therefore we use a BigDecimal.
     BigDecimal pBDecimal = new BigDecimal(Constants.PB);
     return pBDecimal.multiply(BigDecimal.valueOf(ret)).longValue();
   } else {
     throw new IllegalArgumentException("Fail to parse " + ori + " to bytes");
   }
 }
示例#10
0
    /** Set the expected and actual values from their string representations */
    private void setValuesFromStrings() {
      String blurb = "";
      String origEv = getEv();
      String origAv = getAv();
      Currency curr = Currency.getInstance(Locale.getDefault());
      String currSymbol = curr.getSymbol();
      setAv(getAv().replace(currSymbol, ""));
      setEv(getEv().replace(currSymbol, ""));

      if (!getComp().equalsIgnoreCase("between")) {
        try {
          expected = BigDecimal.valueOf(Double.valueOf(getEv()));
        } catch (Exception ex) {
          blurb = "Invalid (expected) Currency value: " + Util.sq(origEv) + "  ";
        }
      }

      try {
        actual = BigDecimal.valueOf(Double.valueOf(getAv()));
      } catch (Exception ex) {
        blurb += "Invalid (actual) Currency value: " + Util.sq(origAv) + "  ";
      }

      if (!isBlank(blurb)) {
        isSpecError = true;
        addError(blurb + "Verification aborted.");
      }
    } // setValuesFromStrings
示例#11
0
 private int convertPercentToByte(PercentType percent) {
   return percent
       .value
       .multiply(BigDecimal.valueOf(255))
       .divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP)
       .intValue();
 }
示例#12
0
 public static Long getLong(Object str, Long defaultValue) {
   if (str == null || "null" == str) {
     return defaultValue;
   }
   BigDecimal db = new BigDecimal(ConvertUtils.getString(str, "0"));
   return Long.valueOf(db.toPlainString());
 }
示例#13
0
 private void updateFundShare(EtfReportInfo etfReportInfo) throws AccountException {
   BigDecimal fundShare = etfReportInfo.getFillShare();
   if (ETFTradeTypeConsts.ETF_ADMIN_REDEEM.equals(etfReportInfo.getTradeType())) {
     fundShare = fundShare.negate();
   }
   fundService.updateFundShare(etfReportInfo.getFundId(), fundShare);
 }
示例#14
0
public class Converter {

  public static final int BIGDECIMAL_ROUNDING = BigDecimal.ROUND_HALF_EVEN;
  public static final int BIGDECIMAL_SCALE = 7;
  public static final BigDecimal SIXTY = BigDecimal.valueOf(60);
  public static final BigDecimal THOUSAND = BigDecimal.valueOf(1000);

  public static BigDecimal getDistanceFromSpeedAndTime(
      final BigDecimal speedInMPH, final long timeInMilliseconds) {
    final BigDecimal timeInSeconds =
        BigDecimal.valueOf(timeInMilliseconds)
            .divide(Converter.THOUSAND, Converter.BIGDECIMAL_SCALE, Converter.BIGDECIMAL_ROUNDING);
    final BigDecimal timeInMinutes =
        timeInSeconds.divide(
            Converter.SIXTY, Converter.BIGDECIMAL_SCALE, Converter.BIGDECIMAL_ROUNDING);
    final BigDecimal timeInHours =
        timeInMinutes.divide(
            Converter.SIXTY, Converter.BIGDECIMAL_SCALE, Converter.BIGDECIMAL_ROUNDING);
    return speedInMPH.multiply(timeInHours);
  }

  public static long getTimeFromSpeedAndDistance(
      final BigDecimal speedInMPH, final BigDecimal distanceInMiles) {
    final double speed = speedInMPH.doubleValue();
    final double distance = distanceInMiles.doubleValue();
    final double result = (distance * 3600000.0d) / speed;
    return Math.round(result);
  }
}
  @SuppressWarnings("unchecked")
  public String execute() throws Exception {
    Context context = getContext();
    Context sessionContext = this.getSessionContext();
    String cstNo = sessionContext.getDataAsStr("cstNo");
    String operChannel = sessionContext.getDataAsStr("operChannel");
    Context parentContext = context.getParent();
    String flowNo = parentContext.getDataAsStr("flowNo");
    context.put("accountNo", accNo);
    context.put("beginDate", fromDate);
    context.put("flowNo", flowNo);
    context.put("endDate", toDate);
    context.put("cashFlag", "1");
    context.put("currency", "01");
    context.put("sortType", "1");
    context.put("pageNo", pageNo);
    context.put("pageSize", PersonConstants.APP_PAGE_SIZE + "");

    context.put("operChannel", operChannel);
    context.put("cstNo", cstNo);

    IcopClientManager.callChannelService(context, "PSVR000003");
    detailList2 = (List<Map<String, Object>>) context.getDataElement("accountDetailList");

    if (detailList2 != null && detailList2.size() > 0) {
      for (int i = 0; i < detailList2.size(); i++) {
        Map<String, Object> map = detailList2.get(i);
        BigDecimal creditamt = new BigDecimal((String) map.get("creditamt"));
        creditamtSum = creditamtSum.add(creditamt);
        BigDecimal debitamt = new BigDecimal((String) map.get("debitamt"));
        debitamtSum = debitamtSum.add(debitamt);

        map.put(
            "currency",
            EBWebContextUtil.getAprShowMsg("CURRENCY_TYPE", (String) map.get("currency")));
        map.put(
            "loanFlagTxt",
            EBWebContextUtil.getAprShowMsg("LOANFLAG_TYPE", (String) map.get("loanFlag")));
        map.put("accountName", cstNameHost);

        map.put("accountNo", accNo);
        detailList.add(map);
      }
    }
    if (!StringUtil.isEmpty(type)) {
      if ("txt".equals(type)) {
        inputStream = generateTxt(detailList);
        contentType = MimeType.TXT.toString();
      } else if ("xls".equals(type)) {
        inputStream = generateExcel(detailList);
        contentType = MimeType.XLS.toString();
      } else if ("pdf".equals(type)) {
        inputStream = generatePdf(detailList);
        contentType = MimeType.PDF.toString();
      }
    }
    filename = fromDate + "-" + toDate + "." + type;

    return SUCCESS;
  }
  /**
   * 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);
    }
  }
示例#17
0
 public double getDB(LocatorAndNoiseMeterThread t) { // The typical VU scale is from −20 to +3
   Synth.startEngine(Synth.FLAG_ENABLE_INPUT); // flag necessary for lineIn
   PeakFollower pd = new PeakFollower();
   PeakFollower follower = new PeakFollower();
   pd.start();
   LineIn lineIn = new LineIn();
   lineIn.start();
   lineIn.output.connect(
       0, pd.input, 0); // connects the signal you want to analyze to the right detector
   try { // we find the peak within 100msec and keep the avg over 2sec
     for (int i = 0; i < 20; i++) { // polls the detector 10 times a second for 2 seconds
       double peak = pd.output.get();
       if (peak != 0) // it may happen in the beginning when there is not enough output
       movingAVG(AudioMath.amplitudeToDecibels(peak));
       if (t != null) t.progressed(50 / 20);
       Thread.sleep(100);
     }
     Synth.stopEngine();
   } catch (SynthException e) {
     throw new Issue("Jsyn engine cannot be stopped.");
   } catch (InterruptedException e) {
     throw new Issue(
         "Interrupted while waiting for "
             + "next noise intensity measurement. Multiple measurements take place for convenience.");
   }
   BigDecimal bd = new BigDecimal(this.m_n);
   BigDecimal rounded = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
   this.n = 0;
   this.m_n = 0.0;
   return rounded.doubleValue();
 }
  public static double toDouble(Object a) throws HsqlException {

    double value;

    if (a instanceof java.lang.Double) {
      return ((Double) a).doubleValue();
    } else if (a instanceof BigDecimal) {
      BigDecimal bd = (BigDecimal) a;

      value = bd.doubleValue();

      int signum = bd.signum();
      BigDecimal bdd = new BigDecimal(value + signum);

      if (bdd.compareTo(bd) != signum) {
        throw Error.error(ErrorCode.X_22003);
      }
    } else if (a instanceof Number) {
      value = ((Number) a).doubleValue();
    } else {
      throw Error.error(ErrorCode.X_22501);
    }

    return value;
  }
示例#19
0
  private static BigDecimal getAmountForType(
      final Iterable<PaymentTransaction> transactions, final TransactionType transactiontype) {
    BigDecimal result = BigDecimal.ZERO;
    BigDecimal processedResult = BigDecimal.ZERO;
    boolean shouldUseProcessedAmount = true;

    for (final PaymentTransaction transaction : transactions) {
      if (transaction.getTransactionType() != transactiontype
          || !TransactionStatus.SUCCESS.equals(transaction.getTransactionStatus())) {
        continue;
      }

      result = result.add(transaction.getAmount());

      shouldUseProcessedAmount =
          shouldUseProcessedAmount
              && transaction.getCurrency().equals(transaction.getProcessedCurrency())
              && transaction.getProcessedAmount() != null;
      processedResult =
          shouldUseProcessedAmount
              ? processedResult.add(transaction.getProcessedAmount())
              : BigDecimal.ZERO;

      // For multi-step AUTH, don't sum the individual transactions
      if (TransactionType.AUTHORIZE.equals(transactiontype)) {
        break;
      }
    }

    return shouldUseProcessedAmount ? processedResult : result;
  }
 private void adjustIncomingPosition(Queue<PositionElement> longs, Queue<PositionElement> shorts) {
   if (mIncomingPosition.signum() == 1) {
     longs.add(new PositionElement(mIncomingPosition, mClosingPrice));
   } else if (mIncomingPosition.signum() == -1) {
     shorts.add(new PositionElement(mIncomingPosition.negate(), mClosingPrice));
   }
 }
  /**
   * If the SECURITY_ID has a class code type A (Alternative Investments), the system must validate
   * that the total END_SEC_T: SEC_CVAL for the SECURITY_ID plus the END_TRAN_LN_T:TRAN_AMT does not
   * exceed the value in END_SEC_T: CMTMNT_AMT for the Security. If it does, the transaction should
   * not be allowed.
   *
   * @return true if valid, false otherwise
   */
  protected boolean validateTaxLotsCostAndTransactionAmountLessOrEqualToSecurityCommitment(
      AssetIncreaseDocument assetIncreaseDocument) {
    boolean isValid = true;

    if (assetIncreaseDocument.getTargetTransactionSecurity() != null
        && assetIncreaseDocument.getTargetTransactionSecurity().getSecurity() != null
        && assetIncreaseDocument.getTargetTransactionSecurity().getSecurity().getClassCode() != null
        && EndowConstants.ClassCodeTypes.ALTERNATIVE_INVESTMENT.equalsIgnoreCase(
            assetIncreaseDocument
                .getTargetTransactionSecurity()
                .getSecurity()
                .getClassCode()
                .getClassCodeType())) {

      BigDecimal totalTransactionLinesAmt = BigDecimal.ZERO;
      BigDecimal securityCommitmentAmt = BigDecimal.ZERO;
      BigDecimal securityCarryValue = BigDecimal.ZERO;

      if (assetIncreaseDocument.getTargetTransactionLines() != null) {
        for (EndowmentTransactionLine transactionLine :
            assetIncreaseDocument.getTargetTransactionLines()) {

          // add to total amount
          totalTransactionLinesAmt =
              totalTransactionLinesAmt.add(
                  transactionLine.getTransactionAmount().bigDecimalValue());
        }
      }

      if (assetIncreaseDocument.getTargetTransactionSecurity() != null
          && assetIncreaseDocument.getTargetTransactionSecurity().getSecurity() != null) {
        if (assetIncreaseDocument.getTargetTransactionSecurity().getSecurity().getCommitmentAmount()
            != null) {
          securityCommitmentAmt =
              assetIncreaseDocument
                  .getTargetTransactionSecurity()
                  .getSecurity()
                  .getCommitmentAmount();
        }
        if (assetIncreaseDocument.getTargetTransactionSecurity().getSecurity().getCarryValue()
            != null) {
          securityCarryValue =
              assetIncreaseDocument.getTargetTransactionSecurity().getSecurity().getCarryValue();
        }
      }

      isValid =
          (securityCarryValue.add(totalTransactionLinesAmt)).compareTo(securityCommitmentAmt) <= 0;

      if (!isValid) {
        putFieldError(
            getErrorPrefix(assetIncreaseDocument.getTargetTransactionLine(0), 0)
                + EndowPropertyConstants.TRANSACTION_LINE_TRANSACTION_AMOUNT,
            EndowKeyConstants.EndowmentTransactionDocumentConstants
                .ERROR_TRANSACTION_SECURITY_COMMITMENT_AMT);
      }
    }

    return isValid;
  }
 private BigDecimal getPosition() {
   BigDecimal position = mIncomingPosition;
   for (Trade<?> trade : mTrades) {
     position = position.add(trade.getQuantity());
   }
   return position;
 }
 /**
  * Calculate of Nyquist velocity
  *
  * @param prf PRF in Hertz
  * @param wave wavelength in 1/100 of centimeters
  * @return float value of Nyquist velocity in m/sec with precision of two decimal
  */
 static float calcNyquist(int prf, int wave) {
   double tmp = (prf * wave * 0.01) * 0.25;
   tmp = tmp * 0.01; // Make it m/sec
   BigDecimal bd = new BigDecimal(tmp);
   BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN);
   return result.floatValue();
 }
示例#24
0
 private static JsonValue decimalEval(JsonNumber v1, JsonNumber v2, int op) {
   BigDecimal n1 = v1.decimalValue();
   BigDecimal n2 = v2.decimalValue();
   BigDecimal n3;
   switch (op) {
     case PLUS:
       {
         n3 = n1.add(n2, MathContext.DECIMAL128);
         break;
       }
     case MINUS:
       {
         n3 = n1.subtract(n2, MathContext.DECIMAL128);
         break;
       }
     case MULTIPLY:
       {
         n3 = n1.multiply(n2, MathContext.DECIMAL128);
         break;
       }
     case DIVIDE:
       {
         try {
           n3 = n1.divide(n2, MathContext.DECIMAL128);
         } catch (ArithmeticException e) {
           // TODO: need +INF, -INF, and NaN
           return null;
         }
         break;
       }
     default:
       throw new RuntimeException("invalid op:" + op);
   }
   return new JsonDecimal(n3);
 }
 /**
  * Calculate data values from raw ingest data
  *
  * @param recHdr java.util.Map object with values for calculation
  * @param dty type of data ( "Total_Power", "Reflectivity", "Velocity", "Width",
  *     "Differential_Reflectivity")
  * @param data 1-byte input value
  * @return float value with precision of two decimal
  */
 static float calcData(Map<String, Number> recHdr, short dty, byte data) {
   short[] coef = {1, 2, 3, 4}; // MultiPRF modes
   short multiprf = recHdr.get("multiprf").shortValue();
   float vNyq = recHdr.get("vNyq").floatValue();
   double temp = -999.99;
   switch (dty) {
     default: // dty=1,2 -total_power, reflectivity (dBZ)
       if (data != 0) {
         temp = (((int) data & 0xFF) - 64) * 0.5;
       }
       break;
     case 3: // dty=3 - mean velocity (m/sec)
       if (data != 0) {
         temp = ((((int) data & 0xFF) - 128) / 127.0) * vNyq * coef[multiprf];
       }
       break;
     case 4: // dty=4 - spectrum width (m/sec)
       if (data != 0) {
         double v = ((((int) data & 0xFF) - 128) / 127.0) * vNyq * coef[multiprf];
         temp = (((int) data & 0xFF) / 256.0) * v;
       }
       break;
     case 5: // dty=5 - differential reflectivity (dB)
       if (data != 0) {
         temp = ((((int) data & 0xFF) - 128) / 16.0);
       }
       break;
   }
   BigDecimal bd = new BigDecimal(temp);
   BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN);
   return result.floatValue();
 }
  protected void changeShapeSize(
      GraphicsType annType,
      NodeType node,
      BigDecimal newHeight,
      BigDecimal newWidth,
      Map<String, AnnotationData> annotations) {
    super.changeShapeSize(annType, node, newHeight, newWidth, annotations);

    BigDecimal oldH = annType.getSize().getHeight();
    BigDecimal oldW = annType.getSize().getWidth();
    BigDecimal oldX = annType.getPosition().get(0).getX();
    BigDecimal oldY = annType.getPosition().get(0).getY();

    BigDecimal newX = oldW.subtract(newWidth).divide(divisor).add(oldX);
    BigDecimal newY = oldH.subtract(newHeight).divide(divisor).add(oldY);

    SizeType size = new SizeType();
    size.setHeight(newHeight);
    size.setWidth(newWidth);
    PositionType position = new PositionType();
    position.setX(newX);
    position.setY(newY);

    annType.setSize(size);
    annType.getPosition().remove(0);
    annType.getPosition().add(position);

    annotations.put(
        node.getId(), new AnnotationData(oldX, oldY, newX, newY, oldH, oldW, newHeight, newWidth));
  }
 /** Test for execute(). */
 @Test
 public void testExecute() {
   AbsoluteValueBigDecimal calc = new AbsoluteValueBigDecimal();
   BigDecimal input = new BigDecimal(-6).setScale(3);
   Object actual = calc.execute(input);
   Assert.assertEquals(input.abs(), actual);
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     return super.write(buff, obj);
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED);
         DataUtils.writeVarInt(buff, scale);
       }
       DataUtils.writeVarLong(buff, b.longValue());
     } else {
       buff.put((byte) TYPE_BIG_DECIMAL);
       DataUtils.writeVarInt(buff, scale);
       byte[] bytes = b.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
示例#29
0
 /**
  * check if the value is lower or equal than...
  *
  * @param ac the validation context
  * @param property the property the value is defined in
  * @throws InvalidParamException
  */
 public void checkLowerEqualThan(ApplContext ac, double d, CssProperty property)
     throws InvalidParamException {
   BigDecimal other = BigDecimal.valueOf(d);
   if (value.compareTo(other) > 0) {
     throw new InvalidParamException("lowerequal", toString(), other.toPlainString(), ac);
   }
 }
示例#30
0
 @Override
 public void write(WriteBuffer buff, Object obj) {
   if (!isBigDecimal(obj)) {
     super.write(buff, obj);
     return;
   }
   BigDecimal x = (BigDecimal) obj;
   if (BigDecimal.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_0);
   } else if (BigDecimal.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_DECIMAL_1);
   } else {
     int scale = x.scale();
     BigInteger b = x.unscaledValue();
     int bits = b.bitLength();
     if (bits < 64) {
       if (scale == 0) {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL);
       } else {
         buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED).putVarInt(scale);
       }
       buff.putVarLong(b.longValue());
     } else {
       byte[] bytes = b.toByteArray();
       buff.put((byte) TYPE_BIG_DECIMAL).putVarInt(scale).putVarInt(bytes.length).put(bytes);
     }
   }
 }