Example #1
0
  private int start(int rounding, int iterations) {
    BigDecimal three = new BigDecimal("3");
    BigDecimal two = new BigDecimal("2");
    MathContext division = new MathContext((int) Math.round(rounding), RoundingMode.HALF_UP);

    BigDecimal x0 = new BigDecimal("5.0");
    BigDecimal x1 = new BigDecimal("5.0");

    for (int i = 0; i < iterations; i++) {
      /*x1 = x0.pow(2);
      System.out.println("1: " + x1.toPlainString());
      x1 = x1.subtract(three);
      System.out.println("2: " + x1.toPlainString());
      x1 = x1.divide(x0.multiply(two), division);
      System.out.println("3: " + x1.toPlainString());
      x0 = x0.subtract(x1);
      System.out.println("x0: " + x1.toPlainString());*/
      x1 = x0.subtract((x0.pow(2).subtract(three)).divide(x0.multiply(two), division));
      x0 = x1;
      // if(i % 10 == 0) { System.out.println(i); }
    }
    String digits1 = x1.toString();
    x1 = x0.subtract((x0.pow(2).subtract(three)).divide(x0.multiply(two), division));
    x0 = x1;
    String digits2 = x1.toString();

    // System.out.println("Sqrt(3) = " + x1.toPlainString());
    return checkDigits(digits1, digits2);
  }
Example #2
0
  public static void main(String args[]) {

    double value = 0.012;
    double pSum = value + value + value;
    System.out.println("sum of primitive" + pSum);
    System.out.println("===========");

    String strValue = Double.toString(value);
    BigDecimal bigValue = new BigDecimal(strValue);

    BigDecimal bSum = bigValue.add(bigValue).add(bigValue);

    BigDecimal b = new BigDecimal(value);

    System.out.println("Sum of BigDecimals: " + bSum.toString());

    double res, num = 0.012;
    res = num * 3;
    System.out.println("==========");
    System.out.println("res:   " + res);
    String strNum = Double.toString(num);
    BigDecimal bigNum = new BigDecimal(strNum);
    BigDecimal bSum1 = bigNum.add(bigNum).add(bigNum);
    System.out.println("new num: " + bSum1.toString());
  }
  /**
   * Create the time delta string for an edge given the min and max ITimes within it, rounding to
   * the specified number of significant digits.
   *
   * @return If min==max, returns "min". Else, returns "[min,max]"
   */
  protected String getITimeString(ITime timeMin, ITime timeMax, int sigDigits) {
    // Make time string
    if (timeMin != null && timeMax != null) {

      // Round the times to a few significant digits for readability
      BigDecimal timeMinDec =
          new BigDecimal(timeMin.toString())
              .round(new MathContext(sigDigits, RoundingMode.HALF_EVEN));
      BigDecimal timeMaxDec =
          new BigDecimal(timeMax.toString())
              .round(new MathContext(sigDigits, RoundingMode.HALF_EVEN));

      // Remove trailing zeros and periods
      String timeMinStr = removeTrailingZeros(timeMinDec.toString());
      String timeMaxStr = removeTrailingZeros(timeMaxDec.toString());

      // String is range if min != max time or else just the single time
      // if they are equal
      if (!timeMinStr.equals(timeMaxStr)) {
        return "[" + timeMinStr + "," + timeMaxStr + "]";
      }
      {
        return timeMinStr;
      }
    }
    {
      return "";
    }
  }
Example #4
0
  @Override
  public String toString() {
    StringBuilder b = new StringBuilder();

    b.append("currency: ").append(currency).append('\n');
    b.append("bankId: ").append(bankId).append('\n');
    b.append("accountId: ").append(accountId).append('\n');
    b.append("accountType: ").append(accountType).append('\n');
    b.append("dateStart: ").append(dateStart.toString()).append('\n');
    b.append("dateEnd: ").append(dateEnd.toString()).append('\n');
    b.append("ledgerBalance: ").append(ledgerBalance.toString()).append('\n');
    b.append("ledgerBalanceDate: ").append(ledgerBalanceDate.toString()).append('\n');

    if (availBalance != null) {
      b.append("availBalance: ").append(availBalance.toString()).append('\n');
    }

    if (availBalanceDate != null) {
      b.append("availBalanceDate: ").append(availBalanceDate.toString()).append('\n');
    }

    for (ImportTransaction t : getTransactions()) {
      b.append(t.toString()).append('\n');
    }

    return b.toString();
  }
Example #5
0
  /** 间隔固定时间打印进度信息. */
  protected void printProgressMessage(final int currentRequests) {
    long currentTime = System.currentTimeMillis();

    if (currentTime > nextPrintTime) {
      long lastIntervalMillis = parent.intervalMillis + (currentTime - nextPrintTime);
      nextPrintTime = currentTime + parent.intervalMillis;

      long lastRequests = currentRequests - previousRequests;

      long totalTimeMillis = currentTime - parent.startTime.getTime();
      long totalTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(totalTimeMillis);

      long totalTps = (currentRequests * 1000) / totalTimeMillis;
      long lastTps = (lastRequests * 1000) / lastIntervalMillis;

      BigDecimal lastLatency =
          new BigDecimal(lastIntervalMillis)
              .divide(new BigDecimal(lastRequests), 2, BigDecimal.ROUND_HALF_UP);
      BigDecimal totalLatency =
          new BigDecimal(totalTimeMillis)
              .divide(new BigDecimal(currentRequests), 2, BigDecimal.ROUND_HALF_UP);

      System.out.printf(
          "Thread %02d process %,d requests after %s seconds. Last tps/latency is %,d/%sms. Total tps/latency is %,d/%sms.\n",
          taskSequence,
          currentRequests,
          totalTimeSeconds,
          lastTps,
          lastLatency.toString(),
          totalTps,
          totalLatency.toString());

      previousRequests = currentRequests;
    }
  }
 // 密码加密
 private static String Encryption(String oldPwd) {
   String newPwd = "0";
   BigDecimal oldPwdBD = new BigDecimal(oldPwd);
   BigDecimal tempYPwd = oldPwdBD.multiply(new BigDecimal("135791"));
   int tempYPwdLen = tempYPwd.toString().length();
   String tempTPwd = "";
   if (tempYPwdLen >= 12) {
     tempTPwd = tempYPwd.toString().substring(1, 7);
   } else if (tempYPwdLen < 12 && tempYPwdLen >= 5) {
     tempTPwd = tempYPwd.toString().substring(0, tempYPwd.toString().length() - 5);
   } else {
     tempTPwd = tempYPwd.toString();
   }
   BigDecimal tempTPwdBD = new BigDecimal(tempTPwd);
   BigDecimal tempZPwdBD = tempTPwdBD.add(oldPwdBD);
   if (tempZPwdBD.intValue() < 1000000) {
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791"));
     newPwd = tempZPwdBD.abs().toString();
   } else {
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("1000000"));
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791"));
     newPwd = tempZPwdBD.abs().toString();
   }
   // 如果netPwd最后获取的是0,则加密后的密码为999888
   if (newPwd.equals("0")) {
     return "999888";
   } else {
     StringBuilder tempNewPwd = new StringBuilder();
     for (int x = 0; x < 6 - newPwd.length(); x++) {
       tempNewPwd.append("0");
     }
     tempNewPwd.append(newPwd);
     return tempNewPwd.toString();
   }
 }
Example #7
0
  public static final AccountTypeWS getWS(
      Integer id,
      Integer entityId,
      String invoiceDesign,
      Date dateCreated,
      BigDecimal creditNotificationLimit1,
      BigDecimal creditNotificationLimit2,
      BigDecimal creditLimit,
      InvoiceDeliveryMethodDTO invoiceDeliveryMethod,
      Integer currencyId,
      Integer languageId,
      String description,
      MainSubscriptionWS mainSubscription,
      Set<AccountInformationTypeDTO> informationTypes,
      Set<PaymentMethodTypeDTO> paymentMethodTypes,
      Integer preferredNotificationAitId) {

    AccountTypeWS ws = new AccountTypeWS();
    ws.setId(id);
    ws.setEntityId(entityId);
    ws.setInvoiceDesign(invoiceDesign);
    ws.setDateCreated(dateCreated);
    ws.setCreditNotificationLimit1(
        creditNotificationLimit1 != null ? creditNotificationLimit1.toString() : null);
    ws.setCreditNotificationLimit2(
        creditNotificationLimit2 != null ? creditNotificationLimit2.toString() : null);
    ws.setCreditLimit(creditLimit != null ? creditLimit.toString() : null);
    ws.setInvoiceDeliveryMethodId(
        invoiceDeliveryMethod != null ? invoiceDeliveryMethod.getId() : null);
    ws.setCurrencyId(currencyId);
    ws.setLanguageId(languageId);
    ws.setMainSubscription(mainSubscription);

    if (description != null) {
      ws.setName(description, Constants.LANGUAGE_ENGLISH_ID);
    }

    if (null != informationTypes && informationTypes.size() > 0) {
      List<Integer> informationTypeIds = new ArrayList<Integer>();
      for (AccountInformationTypeDTO ait : informationTypes) {
        informationTypeIds.add(ait.getId());
      }
      if (!informationTypeIds.isEmpty()) {
        ws.setInformationTypeIds(
            informationTypeIds.toArray(new Integer[informationTypeIds.size()]));
      }
    }

    if (null != paymentMethodTypes && paymentMethodTypes.size() > 0) {
      List<Integer> paymentMethodTypeIds = new ArrayList<Integer>(0);
      for (PaymentMethodTypeDTO paymentMethodType : paymentMethodTypes) {
        paymentMethodTypeIds.add(paymentMethodType.getId());
      }
      ws.setPaymentMethodTypeIds(
          paymentMethodTypeIds.toArray(new Integer[paymentMethodTypeIds.size()]));
    }

    ws.setpreferredNotificationAitId(preferredNotificationAitId);
    return ws;
  }
 @Override
 public void acaoFinalizar() {
   if (validarFormulario()) {
     String idContaOrigem = contaOrigem.getSelectionModel().getSelectedItem().getIdCategoria();
     String idContaDestino = contaDestino.getSelectionModel().getSelectedItem().getIdCategoria();
     if (acao == Acao.CADASTRAR) {
       Transferencia item =
           new Transferencia(
               null,
               idContaOrigem,
               idContaDestino,
               itemController.getIdItem(),
               descricao.getText(),
               valor.getText(),
               data.getValue(),
               Datas.getHoraAtual());
       item.cadastrar();
       new Conta().alterarSaldo(Operacao.DECREMENTAR, idContaOrigem, valor.getText());
       new Conta().alterarSaldo(Operacao.INCREMENTAR, idContaDestino, valor.getText());
       Kernel.principal.acaoTransferencia();
       Janela.showTooltip(Status.SUCESSO, idioma.getMensagem("operacao_sucesso"), Duracao.CURTA);
       Animacao.fadeInOutClose(formulario);
     } else {
       Boolean contaOrigemMudou = !(Modelo.getIdContaOrigem().equals(idContaOrigem));
       if (contaOrigemMudou) {
         new Conta()
             .alterarSaldo(Operacao.INCREMENTAR, Modelo.getIdContaOrigem(), Modelo.getValor());
         new Conta().alterarSaldo(Operacao.DECREMENTAR, idContaOrigem, Modelo.getValor());
       }
       Modelo.setIdContaOrigem(contaOrigem.getValue());
       Boolean contaDestinoMudou = !(Modelo.getIdContaDestino().equals(idContaDestino));
       if (contaDestinoMudou) {
         new Conta()
             .alterarSaldo(Operacao.DECREMENTAR, Modelo.getIdContaDestino(), Modelo.getValor());
         new Conta().alterarSaldo(Operacao.INCREMENTAR, idContaDestino, Modelo.getValor());
       }
       Modelo.setIdContaDestino(contaDestino.getValue());
       Boolean valorMudou = !(Modelo.getValor().equals(valor.getText()));
       if (valorMudou) {
         BigDecimal valorDiferenca = new BigDecimal(Modelo.getValor());
         valorDiferenca = valorDiferenca.subtract(new BigDecimal(valor.getText()));
         new Conta()
             .alterarSaldo(
                 Operacao.INCREMENTAR, Modelo.getIdContaOrigem(), valorDiferenca.toString());
         new Conta()
             .alterarSaldo(
                 Operacao.DECREMENTAR, Modelo.getIdContaDestino(), valorDiferenca.toString());
       }
       Modelo.setValor(valor.getText());
       Modelo.setDescricao(descricao.getText());
       Modelo.setData(data.getValue());
       Modelo.alterar();
       Kernel.principal.acaoTransferencia();
       Janela.showTooltip(Status.SUCESSO, idioma.getMensagem("operacao_sucesso"), Duracao.CURTA);
       Animacao.fadeInOutClose(formulario);
     }
   }
 }
Example #9
0
 private static void _checkConvertibility(@Nonnull final BigDecimal aSize) {
   if (aSize.compareTo(CGlobal.BIGDEC_MAX_LONG) > 0)
     throw new IllegalArgumentException(
         "The passed BigDecimal is too large to be converted into a long value: "
             + aSize.toString());
   if (aSize.compareTo(CGlobal.BIGDEC_MIN_LONG) < 0)
     throw new IllegalArgumentException(
         "The passed BigDecimal is too small to be converted into a long value: "
             + aSize.toString());
 }
Example #10
0
  private ServicioRep mapEntity(List<Account> list) {
    ServicioRep rep = new ServicioRep();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
    List<TipoPago> tpl = new ArrayList<TipoPago>();
    List<TipoServicio> tsl = new ArrayList<TipoServicio>();
    Map<String, TipoPago> tpMap = new HashMap<String, TipoPago>();
    Map<String, List<Servicio>> tsMap = new HashMap<String, List<Servicio>>();
    for (Account at : list) {
      for (FolioTransaction ft : at.getFolioTransactionCollection()) {
        TipoPago tpago = tpMap.get(ft.getPayId().getPayCode());
        if (tpago == null) {
          tpMap.put(
              ft.getPayId().getPayCode(),
              new TipoPago(ft.getPayId().getPayDesc(), ft.getFtrAmount()));
        } else {
          tpago.setTotal(tpago.getTotal().add(ft.getFtrAmount()));
        }
      }
      for (AccountTransactions act : at.getAccountTransactionsCollection()) {
        if (act.getSrvId() != null) {
          BigDecimal ammt =
              act.getSrvId().getSrvPrice().multiply(new BigDecimal(act.getAtrQuantity()));
          if (MMKeys.AccountsTransactions.STA_PAGADO_KEY.equalsIgnoreCase(
              act.getAtrStatus().getMvaKey())) {
            List<Servicio> sl = tsMap.get(act.getSrvId().getSvtId().getSvtDesc());
            if (sl == null) {
              sl = new ArrayList<Servicio>();
              sl.add(
                  new Servicio(act.getSrvId().getSrvDesc(), act.getAtrQuantity(), ammt.toString()));
              tsMap.put(act.getSrvId().getSvtId().getSvtDesc(), sl);
            } else {
              sl.add(
                  new Servicio(act.getSrvId().getSrvDesc(), act.getAtrQuantity(), ammt.toString()));
            }
          }
        }
      }
    }

    for (TipoPago entry : tpMap.values()) {
      tpl.add(entry);
    }
    for (String key : tsMap.keySet()) {
      tsl.add(new TipoServicio(key, tsMap.get(key)));
    }
    rep.setPymentType(tpl);
    rep.setServiceType(tsl);

    return rep;
  }
Example #11
0
 public static void parameter2(
     int a, java.math.BigDecimal b, java.math.BigDecimal c, java.sql.ResultSet[] rs)
     throws SQLException {
   Connection conn = DriverManager.getConnection("jdbc:default:connection");
   PreparedStatement ps = conn.prepareStatement("insert into PT1 values (?, ?, ?)");
   ps.setInt(1, a);
   ps.setString(2, b.toString());
   ps.setString(3, c.toString());
   ps.executeUpdate();
   ps.close();
   ps = conn.prepareStatement("select a,b,c from PT1 where a = ?");
   ps.setInt(1, a);
   rs[0] = ps.executeQuery();
   conn.close();
 }
 @Override
 public Object getProperty(int propertyIndex) {
   // !!!!! If you have a compilation error here then you are using old version of ksoap2 library.
   // Please upgrade to the latest version.
   // !!!!! You can find a correct version in Lib folder from generated zip file!!!!!
   if (propertyIndex == 0) {
     return GatewayTxnId != null ? GatewayTxnId : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 1) {
     return TrackData != null ? TrackData : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 2) {
     return Amt != null ? Amt.toString() : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 3) {
     return PinBlock != null ? PinBlock : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 4) {
     return TokenValue != null ? TokenValue : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 5) {
     return CardHolderData != null ? CardHolderData : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 6) {
     return AllowDup != null ? AllowDup.toString() : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 7) {
     return EncryptionData != null ? EncryptionData : SoapPrimitive.NullSkip;
   }
   if (propertyIndex == 8) {
     return AdditionalTxnFields != null ? AdditionalTxnFields : SoapPrimitive.NullSkip;
   }
   return null;
 }
  private void obtenerValorPorcentaje(java.math.BigDecimal valorPorcentaje) {

    java.math.BigDecimal porcentaje =
        new java.math.BigDecimal(
            valorPorcentaje == null ? "0.00" : valorPorcentaje.toString().trim());

    java.math.BigDecimal parcial =
        new java.math.BigDecimal(
            tabla.getValueAt(fila, buscarColumna("Parcial", tabla)).toString().trim().isEmpty()
                ? "1.00"
                : tabla.getValueAt(fila, buscarColumna("Parcial", tabla)).toString().trim());

    java.math.BigDecimal porcentajeFinal =
        (porcentaje
            .multiply(parcial)
            .divide(new java.math.BigDecimal("100.00"), 15, java.math.RoundingMode.HALF_EVEN));

    /// PARA PONER EL VALOR DECIMAL EN EL CAMPO PRECIO
    tabla.setValueAt(porcentajeFinal, fila, buscarColumna("Descuento", tabla));

    /// PARA PONER EL VALOR EN SUBTOTAL
    tabla.setValueAt(parcial.subtract(porcentajeFinal), fila, buscarColumna("Subtotal", tabla));

    //        ///PARA PONER EL VALOR ENTERO EN EL CAMPO CANTIDAD
    //        tabla.setValueAt(cantidad.toString().substring(0, cantidad.toString().indexOf(".")),
    //                fila, buscarColumna("Cantidad", tabla));
    tabla.updateUI();
  }
 private String operationReport(
     String header, Deposit dep, BigDecimal balanceBeforeOperation, BigDecimal amount) {
   return header
       + "; "
       + "deposit id : "
       + dep.id
       + "; "
       + "amount : "
       + amount.toString()
       + "; "
       + "initial balance : "
       + balanceBeforeOperation.toString()
       + "; "
       + "balance : "
       + dep.balance.toString();
 }
Example #15
0
 public String getTempId() {
   if (super.getTempId() != null && super.getTempId().trim().length() > 0) {
     return super.getTempId();
   } else {
     return assistFileId == null ? super.getTempId() : assistFileId.toString();
   }
 }
  public String expandBody(MssCFGenContext genContext) {
    final String S_ProcName = "CFDbTestMssCFBindReqMinMaxValueTestUInt64.expandBody() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), "expandBody", 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), "expandBody", 1, "genContext.getGenDef()");
    }

    String ret;

    if (genDef instanceof ICFDbTestReqMinMaxValueObj) {
      BigDecimal testUInt64 = ((ICFDbTestReqMinMaxValueObj) genDef).getRequiredTestUInt64();
      if (testUInt64 == null) {
        throw CFLib.getDefaultExceptionFactory()
            .newNullArgumentException(getClass(), "expandBody", 0, "Value");
      }
      ret = testUInt64.toString();
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(),
              "expandBody",
              "genContext.getGenDef()",
              genDef,
              "ICFDbTestReqMinMaxValueObj");
    }

    return (ret);
  }
Example #17
0
 @Override
 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
   BigDecimal d = (BigDecimal) obj;
   d.stripTrailingZeros();
   toAppendTo.append(d.toString());
   return toAppendTo;
 }
 /** 更新 */
 @RequestMapping(value = "/update", method = RequestMethod.POST)
 public String update(
     String paymentName,
     String partner,
     String key,
     FeeType feeType,
     BigDecimal fee,
     String logo,
     String description,
     @RequestParam(defaultValue = "false") Boolean isEnabled,
     Integer order,
     RedirectAttributes redirectAttributes) {
   PluginConfig pluginConfig = yeepayPlugin.getPluginConfig();
   pluginConfig.setAttribute(PaymentPlugin.PAYMENT_NAME_ATTRIBUTE_NAME, paymentName);
   pluginConfig.setAttribute("partner", partner);
   pluginConfig.setAttribute("key", key);
   pluginConfig.setAttribute(PaymentPlugin.FEE_TYPE_ATTRIBUTE_NAME, feeType.toString());
   pluginConfig.setAttribute(PaymentPlugin.FEE_ATTRIBUTE_NAME, fee.toString());
   pluginConfig.setAttribute(PaymentPlugin.LOGO_ATTRIBUTE_NAME, logo);
   pluginConfig.setAttribute(PaymentPlugin.DESCRIPTION_ATTRIBUTE_NAME, description);
   pluginConfig.setIsEnabled(isEnabled);
   pluginConfig.setOrder(order);
   pluginConfigService.update(pluginConfig);
   addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
   return "redirect:/console/payment_plugin/list.ct";
 }
Example #19
0
 /** Evaluate the result of negate computation */
 @Override
 public String negate(String[] args) {
   BigDecimal number1, result;
   number1 = new BigDecimal(args[0]);
   result = number1.negate();
   return result.toString();
 }
 public String getString() {
   BigDecimal localValue = getBigDecimal();
   if (localValue == null) return null;
   else if (toPlainString == null) return localValue.toString();
   else {
     // use reflection so we can still compile using JDK1.4
     // if we are prepared to require 1.5 to compile then this can be a direct call
     try {
       return (String) toPlainString.invoke(localValue, null);
     } catch (IllegalAccessException e) {
       // can't happen based on the JDK spec
       throw new IllegalAccessError("toPlainString");
     } catch (InvocationTargetException e) {
       Throwable t = e.getTargetException();
       if (t instanceof RuntimeException) {
         throw (RuntimeException) t;
       } else if (t instanceof Error) {
         throw (Error) t;
       } else {
         // can't happen
         throw new IncompatibleClassChangeError("toPlainString");
       }
     }
   }
 }
  private void obtenerPrecio(java.math.BigDecimal valorRetorno) {

    java.math.BigDecimal parcial =
        new java.math.BigDecimal(valorRetorno == null ? "0.00" : valorRetorno.toString().trim());

    java.math.BigDecimal cantidad =
        new java.math.BigDecimal(
            tabla.getValueAt(fila, buscarColumna("Cantidad", tabla)).toString().trim().isEmpty()
                ? "1.00"
                : tabla.getValueAt(fila, buscarColumna("Cantidad", tabla)).toString().trim());

    java.math.BigDecimal precio = parcial.divide(cantidad, 15, java.math.RoundingMode.HALF_EVEN);

    java.math.BigDecimal porcentaje =
        new java.math.BigDecimal(
            tabla.getValueAt(fila, buscarColumna("%", tabla)).toString().trim().isEmpty()
                ? "1.00"
                : tabla.getValueAt(fila, buscarColumna("%", tabla)).toString().trim());

    java.math.BigDecimal valorPorcentaje =
        parcial.multiply(porcentaje).divide(new java.math.BigDecimal("100.00"));
    java.math.BigDecimal valorsubTotal = parcial.subtract(valorPorcentaje);

    tabla.setValueAt(precio, fila, buscarColumna("Precio", tabla));

    tabla.setValueAt(valorPorcentaje, fila, buscarColumna("Descuento", tabla));

    tabla.setValueAt(valorsubTotal, fila, buscarColumna("Subtotal", tabla));
    tabla.updateUI();
  }
Example #22
0
 public Money subtract(Money money2) throws CurrencyMismatchException {
   if (!(this.currency.equals(money2.currency))) {
     throw new CurrencyMismatchException("Incompatible Currency!");
   }
   BigDecimal result = this.moneyValue.subtract(money2.moneyValue);
   return new Money(currency, result.toString());
 }
  public void testNumeric() throws Throwable {

    CallableStatement call = con.prepareCall("{ call Numeric_Proc(?,?,?) }");

    call.registerOutParameter(1, Types.NUMERIC, 15);
    call.registerOutParameter(2, Types.NUMERIC, 15);
    call.registerOutParameter(3, Types.NUMERIC, 15);

    call.executeUpdate();
    java.math.BigDecimal ret = call.getBigDecimal(1);
    assertTrue(
        "correct return from getNumeric () should be 999999999999999.000000000000000 but returned "
            + ret.toString(),
        ret.equals(new java.math.BigDecimal("999999999999999.000000000000000")));

    ret = call.getBigDecimal(2);
    assertTrue(
        "correct return from getNumeric ()",
        ret.equals(new java.math.BigDecimal("0.000000000000001")));
    try {
      ret = call.getBigDecimal(3);
    } catch (NullPointerException ex) {
      assertTrue("This should be null", call.wasNull());
    }
  }
Example #24
0
  public static BigDecimal round(BigDecimal num, int scale) {
    String numStr = num.toString();
    int idx = numStr.lastIndexOf('.');
    scale = (idx > 0) ? Math.min((numStr.length() - (idx + 1)), scale) : 0;

    return num.setScale(scale, BigDecimal.ROUND_HALF_UP);
  }
 /* (non-Javadoc)
  * @see fr.hoteia.qalingo.core.solr.service.ProductSkuSolrService#addOrUpdateProductSku(fr.hoteia.qalingo.core.domain.ProductSku)
  */
 public void addOrUpdateProductSku(
     final ProductSku productSku, final MarketArea marketArea, final Retailer retailer)
     throws SolrServerException, IOException {
   if (productSku.getId() == null) {
     throw new IllegalArgumentException("Id  cannot be blank or null.");
   }
   if (logger.isDebugEnabled()) {
     logger.debug("Indexing productSku " + productSku.getId());
     logger.debug("Indexing productSku " + productSku.getBusinessName());
     logger.debug("Indexing productSku " + productSku.getDescription());
     logger.debug("Indexing productSku " + productSku.getCode());
   }
   ProductSkuSolr productSkuSolr = new ProductSkuSolr();
   productSkuSolr.setId(productSku.getId());
   productSkuSolr.setBusinessname(productSku.getBusinessName());
   productSkuSolr.setDescription(productSku.getDescription());
   productSkuSolr.setCode(productSku.getCode());
   ProductSkuPrice productSkuPrice = productSku.getPrice(marketArea.getId(), retailer.getId());
   if (productSkuPrice != null) {
     BigDecimal salePrice = productSkuPrice.getSalePrice();
     productSkuSolr.setPrice(salePrice.toString());
   }
   productSkuSolrServer.addBean(productSkuSolr);
   productSkuSolrServer.commit();
 }
 public PageResult endWechatOrder(String orderNo, String ip, PageResult result, String openid) {
   String hql = "from BabysitterOrder t where t.orderId = ?";
   BabysitterOrder order = dao.getSingleResultByHQL(BabysitterOrder.class, hql, orderNo);
   if (order == null) {
     result.setResult(ResultInfo.BABYSITTER_ORDER_NULL);
     return result;
   }
   if (order.getState() != Constants.EARNEST_MONEY) {
     result.setResult(ResultInfo.INVALID_ORDER);
     return result;
   }
   BigDecimal orderPrice = new BigDecimal(order.getOrderPrice());
   orderPrice = orderPrice.add(new BigDecimal(0 - order.getOrderFrontPrice()));
   orderPrice = orderPrice.multiply(new BigDecimal(100));
   Map<String, String> params =
       RequestXMLCreater.getInstance()
           .getPayRequestMap(
               order.getGuid(),
               "月嫂尾款",
               order.getOrderId() + BabysitterOrderService.END,
               orderPrice.toString(),
               ip,
               openid);
   String xml =
       RequestXMLCreater.getInstance()
           .buildXmlString(params, Constants.WECHAT_OPENID_PAY_APPSECRET);
   System.out.println("======================>" + xml);
   sendPaymentToWeChatServer(result, order, xml);
   return result;
 }
Example #27
0
  public static BigDecimal get(final BigDecimal n) {

    // Make sure n is a positive number

    if (n.compareTo(ZERO) <= 0) {
      throw new IllegalArgumentException();
    }

    final BigDecimal initialGuess = getInitialApproximation(n);
    BigDecimal lastGuess = ZERO;
    BigDecimal guess = new BigDecimal(initialGuess.toString());

    // Iterate

    iterations = 0;
    boolean more = true;
    while (more) {
      lastGuess = guess;
      guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);
      guess = guess.add(lastGuess);
      guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
      error = n.subtract(guess.multiply(guess));
      if (++iterations >= maxIterations) {
        more = false;
      } else if (lastGuess.equals(guess)) {
        more = error.abs().compareTo(ONE) >= 0;
      }
    }
    return guess;
  }
Example #28
0
  /**
   * Helper method to update a row in the ID_TABLE.
   *
   * @param con A Connection.
   * @param tableName The properly escaped name of the table to identify the row.
   * @param quantity An int with the value of the quantity.
   * @exception Exception Database error.
   */
  private void updateQuantity(Connection con, String tableName, BigDecimal quantity)
      throws Exception {
    StringBuffer stmt = new StringBuffer(quantity.toString().length() + tableName.length() + 50);
    stmt.append("UPDATE ")
        .append(ID_TABLE)
        .append(" SET ")
        .append(COL_QUANTITY)
        .append(" = ")
        .append(quantity)
        .append(" WHERE ")
        .append(COL_TABLE_NAME)
        .append(" = '")
        .append(tableName)
        .append('\'');

    Statement statement = null;

    if (log.isDebugEnabled()) {
      log.debug("updateQuantity: " + stmt.toString());
    }

    try {
      statement = con.createStatement();
      statement.executeUpdate(stmt.toString());
    } finally {
      if (statement != null) {
        statement.close();
      }
    }
  }
  public Date transformarJulianaAGregoria(BigDecimal valor) {
    String j = valor.toString();
    Date date = new Date();
    String primerValor = "";
    if (j.length() == 5) {
      try {
        date = new SimpleDateFormat("yyD").parse(j);
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      primerValor = j.substring(0, 1);
      if (primerValor.equals("1")) {
        String anno = j.substring(1, 3);
        date.setYear(Integer.valueOf("20" + anno) - 1900);
        String s = j.substring(3);
        Date fecha = new Date();
        try {
          fecha = new SimpleDateFormat("D").parse(s);
        } catch (ParseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        fecha.setYear(date.getYear());
        return fecha;
      }
    }

    return date;
  }
  public String render(BigDecimal object) {
    if (object == null) {
      return "";
    }

    return object.toString();
  }