Exemplo n.º 1
0
  @Override
  public Optional<AttributeValidationReport> validate(final Attribute attribute) {
    Preconditions.checkArgument(attribute != null, "The attribute cannot be null.");

    final String name = attribute.getName();

    for (final Serializable value : attribute.getValues()) {
      final BigDecimal bdValue;
      if (value instanceof Number) {
        bdValue = new BigDecimal(value.toString());
      } else {
        continue;
      }

      if (!checkRange(bdValue)) {
        final String violationMessage =
            String.format(
                "%s must be between %s and %s", name, min.toPlainString(), max.toPlainString());
        final AttributeValidationReportImpl report = new AttributeValidationReportImpl();
        report.addViolation(
            new ValidationViolationImpl(
                Collections.singleton(name), violationMessage, Severity.ERROR));
        return Optional.of(report);
      }
    }

    return Optional.empty();
  }
Exemplo n.º 2
0
  private void calculateNextLevel(
      SkyNetID ownID, SkyNetID skyNetCoKey, BigDecimal left, BigDecimal right, int iter) {
    if (iter == 0) {
      coordinatorKey = skyNetCoKey;
      level = iter;
    } else {
      coordinatorKey = skyNetCoKey;
      level = iter;
    }
    if (iter < 100) {
      // call processNextLevel(...), but before split the interval
      // defined by left and right in k subintervals as defined by
      // branchingFactor.
      BigDecimal interval = right.subtract(left);
      BigDecimal intervalStep = interval.divide(new BigDecimal(String.valueOf(branchingFactor)));
      BigDecimal tempLeft = left;
      BigDecimal tempRight = left.add(new BigDecimal(String.valueOf(intervalStep)));
      log.info(
          SkyNetUtilities.getTimeAndNetID(skyNetNode)
              + "is actually in the interval between "
              + left.toPlainString()
              + " and "
              + right.toPlainString()
              + ". The size of the interval is"
              + interval);
      int correctnessCounter = 0;
      while (ownID.getID().compareTo(tempRight) > -1) {
        tempLeft = tempRight;
        tempRight = tempRight.add(new BigDecimal(String.valueOf(intervalStep)));
        if (correctnessCounter < branchingFactor) {
          correctnessCounter++;
        } else {
          log.fatal(
              "There are actually "
                  + (correctnessCounter + 1)
                  + " intervals instead of "
                  + branchingFactor);
        }
      }
      processNextLevel(ownID, tempLeft, tempRight, iter + 1);

    } else {
      skyNetNode.getMetricUpdateStrategy().scheduleNextUpdateEvent();
      parentCoordinator = null;
      if (isRoot) {
        log.warn(SkyNetUtilities.getTimeAndNetID(skyNetNode) + "lost the root-position");
      }
      isRoot = false;
      log.error(
          SkyNetUtilities.getTimeAndNetID(skyNetNode)
              + "is to deep in the tree."
              + "Probably no predecessor in the overlay can be found"
              + " to calculate the 'isRootOf'-method");
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();
    // Output the results
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet ConverterServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet ConverterServlet at " + request.getContextPath() + "</h1>");

    try {
      String amount = request.getParameter("amount");

      if ((amount != null) && (amount.length() > 0)) {
        // convert the amount to a BigDecimal from the request parameter
        BigDecimal d = new BigDecimal(amount);

        // call the ConverterBean.dollarToYen() method to get the amount
        // in Yen
        BigDecimal yenAmount = converter.dollarToYen(d);

        // call the ConverterBean.yenToEuro() method to get the amount
        // in Euros
        BigDecimal euroAmount = converter.yenToEuro(yenAmount);

        out.println("<p>" + amount + " dollars are " + yenAmount.toPlainString() + " yen.</p>");
        out.println(
            "<p>"
                + yenAmount.toPlainString()
                + " yen are "
                + euroAmount.toPlainString()
                + " Euro.</p>");
      } else {
        out.println("<h2>Enter a dorrar amount to convert:</h2>");
        out.println("<form method=\"get\">");
        out.println("<p>$ <input type=\"text\" name=\"amount\" size=\"25\"></p>");
        out.println("<br/>");
        out.println(
            "<input type=\"submit\" value=\"Submit\">" + "<input type=\"reset\" value=\"Reset\">");
        out.println("</form>");
      }
    } finally {
      out.println("</body>");
      out.println("</html>");
      out.close();
    }
  }
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String line = input.nextLine();
    line = line.trim();
    String[] numbers = line.split("[\\+\\- ]+");
    ArrayList<String> signs = new ArrayList<String>();

    Pattern p = Pattern.compile("([\\-\\+])");
    Matcher m = p.matcher(line);

    while (m.find()) {
      String token = m.group(1);
      signs.add(token);
    }

    BigDecimal sum = new BigDecimal(numbers[0]);
    for (int i = 0; i < signs.size(); i++) {

      if (signs.get(i).equals("+")) {
        BigDecimal num = new BigDecimal(numbers[i + 1]);
        sum = sum.add(num);
      } else {
        BigDecimal num = new BigDecimal(numbers[i + 1]);
        sum = sum.subtract(num);
      }
    }
    System.out.printf("%1$s", sum.toPlainString());

    input.close();
  }
Exemplo n.º 5
0
  public static List<DetailModel> getDutyDetaildayInfor(String s) {
    list = new ArrayList<DetailModel>();
    ICollection icoll = null;
    IEnumerator ienum = null;
    icoll = FileTools.getBussCollection("DutyId", s, "DutyDetail");
    ienum = icoll.GetEnumerator();
    if (ienum != null) {
      while (ienum.MoveNext()) {
        BusinessObject bo = (BusinessObject) ienum.get_Current();
        String receiveAlarmpPhone =
            bo.GetField("ReceiveAlarmpPhone").get_NativeValue().toString(); // 得到接收告警手机号码字段对应的值
        BigDecimal big = new BigDecimal(receiveAlarmpPhone);
        String receiveAlarmEmail =
            bo.GetField("ReceiveAlarmEmail").get_NativeValue().toString(); // 得到接收告警邮箱字段对应的值
        String DateTime = bo.GetField("Week").get_NativeValue().toString(); // 得到日期字段对应的值
        String startTime = bo.GetField("StartTime").get_NativeValue().toString(); // 得到开始日期字段对应的值
        String endTime = bo.GetField("EndTime").get_NativeValue().toString(); // 得到结束日期对应的值

        DetailModel detail = new DetailModel(bo);
        detail.setReceiveAlarmpPhone(big.toPlainString());
        detail.setReceiveAlarmEmail(receiveAlarmEmail);
        detail.setWeek(DateTime);
        detail.setStartTime(startTime.substring(11));
        detail.setEndTime(endTime.substring(11));
        list.add(detail);
      }
    }
    return list;
  }
Exemplo n.º 6
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());
 }
  @Override
  public PayInfoResponsePage queryPayCCPC(
      PayCCPCCondition condition, int startIndex, int pageSize) {
    PayInfoResponsePage payInfoResponsePage = new PayInfoResponsePage();
    payInfoResponsePage.setStartIndex(startIndex + "");
    payInfoResponsePage.setPageSize(pageSize + "");

    Page<PayCCPC> page = payCCPCService.queryPayCCPC(condition, startIndex, pageSize);
    List<PayInfoResponse> payInfos = new ArrayList<PayInfoResponse>();
    if (page != null) {
      BigDecimal totalAmt = payCCPCService.countTotalAmount(condition);
      payInfoResponsePage.setTotalSize(page.getTotalCount() + "");
      payInfoResponsePage.setTotalAmount(totalAmt.toPlainString());
      List<PayCCPC> lists = page.getItems();
      for (PayCCPC temp : lists) {
        payInfos.add(payCCPCToPayInfoResponse(temp));
      }
      payInfoResponsePage.setPayInfos(payInfos);
    } else {
      payInfoResponsePage.setTotalSize("0");
      payInfoResponsePage.setTotalAmount("0.00");
      payInfoResponsePage.setPayInfos(payInfos);
    }
    return payInfoResponsePage;
  }
Exemplo n.º 8
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);
   }
 }
 /**
  * Determines if this number represents a special number. A Dozen, a Half-Dozen, a Six-Pack, One
  * Miiiiilion, etc.
  *
  * @param decimal
  * @return
  */
 private static String getSpecialLargeIntegerString(BigDecimal decimal) {
   String number = decimal.toPlainString();
   String returnVal = "" + number;
   switch (number) {
     case "144":
       switch (random.nextInt(2)) {
         case 0:
           returnVal = "One Gross (144)";
           break;
         case 1:
           returnVal = "144";
           break;
         default:
           break;
       }
       break;
     case "1000":
       switch (random.nextInt(2)) {
         case 0:
           returnVal = "One Thousand";
           break;
         case 1:
           returnVal = "144";
           break;
         default:
           break;
       }
       break;
     case "1000000":
       switch (random.nextInt(2)) {
         case 0:
           returnVal = "One Miiiiiiillion";
           break;
         case 1:
           returnVal = "144";
           break;
         default:
           break;
       }
       break;
     case "1000000000":
       switch (random.nextInt(2)) {
         case 0:
           returnVal = "One Biiiiiiillion";
           break;
         case 1:
           returnVal = "144";
           break;
         default:
           break;
       }
       break;
     default:
       // format it nicely
       DecimalFormat formatter = new DecimalFormat("#,###");
       returnVal = formatter.format(decimal);
       break;
   }
   return returnVal;
 }
  // Start editing the cell
  @Override
  protected void startEditing(final Context context, final Element parent, final BigDecimal value) {

    textBox.setValue((value == null ? "" : value.toPlainString()));

    panel.setPopupPositionAndShow(
        new PositionCallback() {
          public void setPosition(int offsetWidth, int offsetHeight) {
            panel.setPopupPosition(
                parent.getAbsoluteLeft() + offsetX, parent.getAbsoluteTop() + offsetY);

            // Focus the first enabled control
            Scheduler.get()
                .scheduleDeferred(
                    new ScheduledCommand() {

                      public void execute() {
                        String text = textBox.getValue();
                        textBox.setFocus(true);
                        textBox.setCursorPos(text.length());
                        textBox.setSelectionRange(0, text.length());
                      }
                    });
          }
        });
  }
Exemplo n.º 11
0
 private static short[] pgNumericVar(BigDecimal n) {
   short ndigits, weight, sign, dscale;
   dscale = (short) n.scale();
   if (dscale < 0) dscale = 0;
   String s = n.toPlainString();
   int lpos = 0;
   sign = NUMERIC_POS;
   if (s.charAt(lpos) == '-') {
     sign = NUMERIC_NEG;
     lpos++;
   }
   int dposl = s.indexOf('.', lpos), dposr;
   if (dposl < 0) dposr = dposl = s.length();
   else dposr = dposl + 1;
   int nleft = (dposl - lpos + 3) / 4;
   weight = (short) (nleft - 1);
   int nright = (s.length() - dposr + 3) / 4;
   ndigits = (short) (nleft + nright);
   while ((ndigits > 0)
       && (pgNumericDigit(s, ndigits - 1, lpos, dposl, dposr, nleft, nright) == 0)) {
     ndigits--;
   }
   short[] digits = new short[ndigits + 4];
   digits[0] = ndigits;
   digits[1] = weight;
   digits[2] = sign;
   digits[3] = dscale;
   for (int i = 0; i < ndigits; i++) {
     digits[i + 4] = pgNumericDigit(s, i, lpos, dposl, dposr, nleft, nright);
   }
   return digits;
 }
Exemplo n.º 12
0
 @Override
 public Map<String, String> makeParams() {
   Map<String, String> result = new HashMap<String, String>();
   result.put(PARAM_PHONE_NUMBER, number);
   result.put(PARAM_AMOUNT, amount.toPlainString());
   return result;
 }
Exemplo n.º 13
0
  /**
   * Returns the given value as a plain string denominated in BTC. The result is unformatted with no
   * trailing zeroes. For instance, an input value of BigInteger.valueOf(150000) nanocoin gives an
   * output string of "0.0015" BTC
   *
   * @param value The value in nanocoins to convert to a string (denominated in BTC)
   * @throws IllegalArgumentException If the input value is null
   */
  public static String bitcoinValueToPlainString(BigInteger value) {
    if (value == null) {
      throw new IllegalArgumentException("Value cannot be null");
    }

    BigDecimal valueInBTC = new BigDecimal(value).divide(new BigDecimal(Utils.COIN));
    return valueInBTC.toPlainString();
  }
 protected String getRandomValue(String baseValue, double randomBound, Field field) {
   Random random = new Random();
   double multiplier = random.nextInt(1) == 1 ? 1.0d : -1.0d;
   BigDecimal randomValue =
       BigDecimal.valueOf(Double.valueOf(baseValue) + randomBound * Math.random() * multiplier);
   randomValue = randomValue.setScale(0, BigDecimal.ROUND_HALF_UP);
   return getValueWithPadding(randomValue.toPlainString(), field);
 }
Exemplo n.º 15
0
  private void checkResponsibility(
      SkyNetID ownID, SkyNetID skyNetCoKey, BigDecimal left, BigDecimal right, int iter) {
    skyNetNode.getSkyNetNodeInfo().setCoordinatorKey(skyNetCoKey);
    log.info(
        " The client "
            + skyNetNode.getSkyNetNodeInfo().toString()
            + " is responsible for the CoordinatorKey "
            + skyNetCoKey.getPlainSkyNetID()
            + " in the interval["
            + left.toPlainString()
            + ";"
            + right.toPlainString()
            + "] @ level "
            + iter);

    ISkyNetMonitor monitor = (ISkyNetMonitor) Simulator.getMonitor();
    ChurnStatisticsAnalyzer csAnalyzer =
        (ChurnStatisticsAnalyzer) monitor.getConnectivityAnalyzer(ChurnStatisticsAnalyzer.class);

    if (iter > 0) {
      // complete the parentSkyNetNode Info
      if (isRoot) {
        log.warn(SkyNetUtilities.getTimeAndNetID(skyNetNode) + "lost the root-position");
        csAnalyzer.lostRootPosition(skyNetNode);
        skyNetNode.getMetricUpdateStrategy().setLastMetricSync(0);
      }
      skyNetNode.getSkyNetNodeInfo().setLevel(iter);
      isRoot = false;
      lookupParentCoordinator();
    } else {
      if (!isRoot) {
        log.warn(SkyNetUtilities.getTimeAndNetID(skyNetNode) + "got the root-position");
        csAnalyzer.gotRootPosition(skyNetNode);
        skyNetNode.getMetricUpdateStrategy().setLastMetricSync(0);
      }
      skyNetNode.getSkyNetNodeInfo().setLevel(iter);

      // Also set the observed level at this point
      skyNetNode.getSkyNetNodeInfo().setObservedLevelFromRoot(0);

      isRoot = true;
      skyNetNode.getAttributeUpdateStrategy().resetOnlyAttributeUpdateStrategy();
      skyNetNode.getMetricUpdateStrategy().sendNextDataUpdate();
    }
  }
Exemplo n.º 16
0
  public static void assertBounds(
      final Number lower, final Number value, final Number upper, final NumberContext precision) {

    final BigDecimal tmpLower = TypeUtils.toBigDecimal(lower, precision);
    final BigDecimal tmpValue = TypeUtils.toBigDecimal(value, precision);
    final BigDecimal tmpUpper = TypeUtils.toBigDecimal(upper, precision);

    if ((tmpValue.compareTo(tmpLower) == -1) || (tmpValue.compareTo(tmpUpper) == 1)) {
      Assert.fail(
          "!("
              + tmpLower.toPlainString()
              + " <= "
              + tmpValue.toPlainString()
              + " <= "
              + tmpUpper.toPlainString()
              + ")");
    }
  }
 String buildInternalId(
     final DateTime messageTimeStamp, final BigDecimal accountId, final Order order) {
   final DateTime dtLondon = messageTimeStamp.withZone(DateTimeZone.forID("Europe/London"));
   final String date = DATE_TIME_FORMATTER.print(dtLondon);
   final long nextIncrement = atomicLong.getAndIncrement();
   return String.format(
       "%s_%s_%s_%s_%s",
       order.getCashier(), order.getProductId(), accountId.toPlainString(), date, nextIncrement);
 }
Exemplo n.º 18
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 warnLowerEqualThan(ApplContext ac, double d, CssProperty property) {
   BigDecimal other = BigDecimal.valueOf(d);
   if (value.compareTo(other) > 0) {
     String[] s = new String[2];
     s[0] = toString();
     s[1] = other.toPlainString() + '%';
     ac.getFrame().addWarning("lowerequal", s);
   }
 }
Exemplo n.º 19
0
  /**
   * Convert a value in bytes to value readable by humans
   *
   * @param bytesValue the bytes value
   * @return the updated value
   */
  public static String toHumanSize(long bytesValue) {
    if (0 == bytesValue) {
      return "0B";
    }
    // it's on base 2
    boolean powerOfTwo = false;
    if ((bytesValue & (bytesValue - 1L)) == 0) {
      powerOfTwo = true;
    }
    // or an exact modulo like 1.5
    long multiple = (long) (bytesValue / 1.5);
    if ((multiple & (multiple - 1L)) == 0) {
      powerOfTwo = true;
    }

    Unit unit = Unit.B;
    // power of two
    if (powerOfTwo) {
      if (bytesValue >= Unit.EiB.value) {
        unit = Unit.EiB;
      } else if (bytesValue >= Unit.PiB.value) {
        unit = Unit.PiB;
      } else if (bytesValue >= Unit.TiB.value) {
        unit = Unit.TiB;
      } else if (bytesValue >= Unit.GiB.value) {
        unit = Unit.GiB;
      } else if (bytesValue >= Unit.MiB.value) {
        unit = Unit.MiB;
      } else if (bytesValue >= Unit.KiB.value) {
        unit = Unit.KiB;
      }
    } else {
      // base 10
      if (bytesValue >= Unit.EB.value) {
        unit = Unit.EB;
      } else if (bytesValue >= Unit.PB.value) {
        unit = Unit.PB;
      } else if (bytesValue >= Unit.TB.value) {
        unit = Unit.TB;
      } else if (bytesValue >= Unit.GB.value) {
        unit = Unit.GB;
      } else if (bytesValue >= Unit.MB.value) {
        unit = Unit.MB;
      } else if (bytesValue >= Unit.KB.value) {
        unit = Unit.KB;
      }
    }

    // one digit float
    double val = (bytesValue / unit.getValue());
    double roundedValue = Math.round(val * 10.0) / 10.0;
    // Strip any trailing 0
    BigDecimal myDecimal = BigDecimal.valueOf(roundedValue);
    BigDecimal updated = myDecimal.stripTrailingZeros();
    return updated.toPlainString() + unit.name();
  }
Exemplo n.º 20
0
  /**
   * Initialize exchange specific settings
   *
   * @throws Exception
   */
  public void initialize(PluginConfig config) throws Exception {
    Properties prop = getConfigProperties(config);
    parseSettings(prop);

    String profitPercent = targetProfit.multiply(new BigDecimal(100)).toPlainString();
    String msg =
        String.format(
            "Current exchange: %s, Fees: %s %%, Scalp amount: %s, target profit: %s, Max num operations: %d, Trend: %s",
            new Object[] {
              exchangeSite,
              fee.toPlainString(),
              scalpAmount.toPlainString(),
              profitPercent,
              maxPendingOperations,
              trend.toString()
            });
    logger.info(msg);
    this.exchange = exchangeFactory.createExchange(exchangeSite);
  }
Exemplo n.º 21
0
 @Override
 @Transient
 public int getScale() {
   final BigDecimal bigDecimal = new BigDecimal("" + bd);
   final String s = bigDecimal.toPlainString();
   final int index = s.indexOf('.');
   if (index < 0) {
     return 0;
   }
   return s.length() - 1 - index;
 }
Exemplo n.º 22
0
  @Test
  public void testBigDecimal() {
    {
      BigDecimal b = new BigDecimal(200).multiply(new BigDecimal(0.5));
      assertEquals("100.0", b.toPlainString());
    }
    {
      BigDecimal b = new BigDecimal(200).divide(new BigDecimal(2));
      assertEquals("100", b.toPlainString());
    }

    {
      BigDecimal b = new BigDecimal(333).multiply(new BigDecimal(0.5));
      assertEquals("166.5", b.toPlainString());
    }
    {
      BigDecimal b = new BigDecimal(333).divide(new BigDecimal(2));
      assertEquals("166.5", b.toPlainString());
    }
  }
 @Override
 public KademliaOverlayID getOverlayID(SkyNetID skyNetID) {
   BigDecimal dec = skyNetID.getID().multiply(upperBound);
   BigInteger kademliaOverlayID = null;
   try {
     kademliaOverlayID = dec.toBigIntegerExact();
   } catch (Exception e) {
     log.fatal("Unable to create exact integer out of " + dec.toPlainString());
   }
   return new KademliaOverlayID(kademliaOverlayID.subtract(BigInteger.ONE), config);
 }
Exemplo n.º 24
0
  @Override
  protected <T> String internalValueToString(
      final T value,
      final Boolean isNullable,
      final Integer maxLength,
      final Integer precision,
      final Integer scale,
      final Boolean isUnicode)
      throws EdmPrimitiveTypeException {

    String result;
    if (value instanceof Long
        || value instanceof Integer
        || value instanceof Short
        || value instanceof Byte
        || value instanceof BigInteger) {
      result = value.toString();
      final int digits = result.startsWith("-") ? result.length() - 1 : result.length();
      if (precision != null && precision < digits) {
        throw new EdmPrimitiveTypeException(
            "The value '" + value + "' does not match the facets' constraints.");
      }

    } else if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) {
      BigDecimal bigDecimalValue;
      try {
        bigDecimalValue =
            value instanceof Double
                ? BigDecimal.valueOf((Double) value)
                : value instanceof Float ? BigDecimal.valueOf((Float) value) : (BigDecimal) value;
      } catch (final NumberFormatException e) {
        throw new EdmPrimitiveTypeException("The value '" + value + "' is not valid.", e);
      }

      final int digits =
          bigDecimalValue.scale() >= 0
              ? Math.max(bigDecimalValue.precision(), bigDecimalValue.scale())
              : bigDecimalValue.precision() - bigDecimalValue.scale();
      if ((precision == null || precision >= digits)
          && (bigDecimalValue.scale() <= (scale == null ? 0 : scale))) {
        result = bigDecimalValue.toPlainString();
      } else {
        throw new EdmPrimitiveTypeException(
            "The value '" + value + "' does not match the facets' constraints.");
      }

    } else {
      throw new EdmPrimitiveTypeException(
          "The value type " + value.getClass() + " is not supported.");
    }

    return result;
  }
  private void obtenerValorPorcentaje(java.math.BigDecimal valorDescuento) {

    try {
      //////////////////////////// ESTO ES PARA OBTENER EL PORCENTAJE
      java.math.BigDecimal parcial =
          new java.math.BigDecimal(
              tabla.getValueAt(fila, buscarColumna("Parcial", tabla)) == null
                      || tabla
                          .getValueAt(fila, buscarColumna("Parcial", tabla))
                          .toString()
                          .trim()
                          .isEmpty()
                  ? "0.00"
                  : tabla.getValueAt(fila, buscarColumna("Parcial", tabla)).toString().trim());

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

      java.math.BigDecimal multiplicacion = descuento.multiply(new java.math.BigDecimal("100.00"));
      java.math.BigDecimal division = cero;

      if (parcial.compareTo(cero) > 0)
        division = multiplicacion.divide(parcial, 15, java.math.RoundingMode.HALF_UP);
      tabla.setValueAt(division.toPlainString(), fila, buscarColumna("%", tabla));

      /// PARA PONER EL SUBTOTAL
      //            table.setValueAt(parcial.subtract(division), fila, buscarColumna("Subtotal"));
      //            if (division.compareTo(mDIShrimp.getCero()) == 0){
      //                table.setValueAt(parcial.subtract(division), fila,
      // buscarColumna("Subtotal"));
      //            } else {
      //                table.setValueAt(division.subtract(parcial), fila,
      // buscarColumna("Subtotal"));
      //            }

      tabla.repaint();
    } catch (Exception e) {
      shrimp.helper.JDVentanaMensajes.showMessageDialog(
          new javax.swing.JFrame(),
          "Ha ocurrido un error inesperado en el formulario",
          javax.swing.JOptionPane.ERROR_MESSAGE,
          javax.swing.JOptionPane.DEFAULT_OPTION,
          e,
          null);
    }

    //        ///PARA PONER EL VALOR ENTERO EN EL CAMPO CANTIDAD
    //        tabla.setValueAt(cantidad.toString().substring(0, cantidad.toString().indexOf(".")),
    //                fila, buscarColumna("Cantidad", tabla));
    tabla.updateUI();
  }
Exemplo n.º 26
0
 private String getStationDescription(Station station) {
   StringBuilder result = new StringBuilder();
   result.append(station.getName());
   BigDecimal distance = station.getDistance();
   String distanceUnits = station.getUnit();
   if (distance != null && distanceUnits != null) {
     result.append(" (");
     result.append(distance.toPlainString());
     result.append(" ");
     result.append(distanceUnits);
     result.append(")");
   }
   return result.toString();
 }
Exemplo n.º 27
0
  // ======================================================================
  // [FUNC] Converts a radical value to BigDecimal.
  private static String rad2dec(String str, BigDecimal rad) {
    BigDecimal bd = new BigDecimal(0);
    int chr = 0;

    for (int i = str.length() - 1, p = 0; i >= 0; i--, p++) {
      chr = Character.toUpperCase(str.charAt(i));
      if (chr >= '0' && chr <= '9') bd = bd.add(rad.pow(p).multiply(new BigDecimal(chr - '0')));
      else if (chr >= 'A' && chr <= 'Z')
        bd = bd.add(rad.pow(p).multiply(new BigDecimal(chr - 'A' + 10)));
      else p--; // Ignore other characters as if they weren't there ;)
    }

    return bd.toPlainString();
  }
  @Test
  public void testBigDecimalJsonUnmarshaller() throws Exception {
    BigDecimal bd = new BigDecimal("1.5");

    StringWriter sw = new StringWriter();
    AwsJsonWriter jw = JsonUtils.getJsonWriter(sw);
    jw.beginObject();
    jw.name("bd");
    jw.value(bd.toPlainString());
    jw.endObject();
    String json = sw.toString();

    StringReader sr = new StringReader(json);
    AwsJsonReader jr = JsonUtils.getJsonReader(sr);
    JsonUnmarshallerContext context = new JsonUnmarshallerContext(jr);
    context.getReader().beginObject();
    context.getReader().nextName();

    SimpleTypeJsonUnmarshallers.BigDecimalJsonUnmarshaller bdUnmarshaller =
        SimpleTypeJsonUnmarshallers.BigDecimalJsonUnmarshaller.getInstance();
    BigDecimal unmarshalledBD = bdUnmarshaller.unmarshall(context);
    assertEquals(unmarshalledBD.toPlainString(), bd.toPlainString());
  }
Exemplo n.º 29
0
 /**
  * Returns the given value in nanocoins as a 0.12 type string. More digits after the decimal place
  * will be used if necessary, but two will always be present.
  */
 public static String bitcoinValueToFriendlyString(BigInteger value) {
   // TODO: This API is crap. This method should go away when we encapsulate money values.
   boolean negative = value.compareTo(BigInteger.ZERO) < 0;
   if (negative) value = value.negate();
   BigDecimal bd = new BigDecimal(value, 8);
   String formatted = bd.toPlainString(); // Don't use scientific notation.
   int decimalPoint = formatted.indexOf(".");
   // Drop unnecessary zeros from the end.
   int toDelete = 0;
   for (int i = formatted.length() - 1; i > decimalPoint + 2; i--) {
     if (formatted.charAt(i) == '0') toDelete++;
     else break;
   }
   return (negative ? "-" : "") + formatted.substring(0, formatted.length() - toDelete);
 }
  @Before
  public void setUp() throws com.yazino.game.api.GameException, WalletServiceException {
    MockitoAnnotations.initMocks(this);

    timeSource = new SettableTimeSource(System.currentTimeMillis());

    command = new CommandWrapper(TABLE_ID, GAME_ID, A_PLAYER.getId(), SESSION_ID, "T");
    command.setRequestId(UUID);
    playerStatisticEventsPublisher = new InMemoryPlayerStatisticEventsPublisher();

    table =
        new Table(
            new com.yazino.game.api.GameType(GAME_TYPE, "Test", Collections.<String>emptySet()),
            BigDecimal.ONE,
            "test",
            true);
    table.setTableId(TABLE_ID);
    table.setTableStatus(TableStatus.open);
    table.setVariationProperties(new HashMap<String, String>());

    when(bufferedGameHostWalletFactory.create(table.getTableId(), command.getRequestId()))
        .thenReturn(bufferedGameHostWallet);
    when(bufferedGameHostWalletFactory.create(table.getTableId()))
        .thenReturn(bufferedGameHostWallet);

    when(auditor.newLabel()).thenReturn(AUDIT_LABEL);
    when(bufferedGameHostWallet.getBalance(Mockito.isA(BigDecimal.class)))
        .thenReturn(BigDecimal.ZERO);

    when(uuidSource.getNewUUID()).thenReturn(NEW_UUID);
    when(auditor.newLabel()).thenReturn(AUDIT_LABEL);
    when(bufferedGameHostWallet.getBalance(Mockito.isA(BigDecimal.class)))
        .thenReturn(ACCOUNT_BALANCE);

    when(gameRules.getGameType()).thenReturn("TEST");

    when(playerRepository.findSummaryByPlayerAndSession(PLAYER_ID, SESSION_ID))
        .thenReturn(
            aPlayerSessionSummary(PLAYER_ID, "Player", PLAYER_ACCOUNT_ID, BigDecimal.valueOf(100)));
    when(playerRepository.findSummaryByPlayerAndSession(PLAYER_ID, null))
        .thenReturn(
            aPlayerSessionSummary(PLAYER_ID, "Player", PLAYER_ACCOUNT_ID, BigDecimal.valueOf(100)));
    when(playerRepository.findSummaryByPlayerAndSession(PLAYER1_ID, null))
        .thenReturn(
            aPlayerSessionSummary(
                PLAYER1_ID, "Player1", PLAYER1_ACCOUNT_ID, BigDecimal.valueOf(200)));
    when(playerRepository.findSummaryByPlayerAndSession(PLAYER2_ID, null))
        .thenReturn(
            aPlayerSessionSummary(
                PLAYER2_ID, "Player2", PLAYER2_ACCOUNT_ID, BigDecimal.valueOf(300)));

    when(chatRepository.getOrCreateForLocation(TABLE_ID.toPlainString()))
        .thenReturn(new ChatChannel(TABLE_ID.toPlainString()));
  }