@Test
  @WithMockUser(roles = "Tutor")
  public void currentMonthBalanceMultipleAppointments() throws Exception {
    Appointment testAppointment1 = new Appointment();
    Appointment testAppointment2 = new Appointment();

    LocalDateTime dateTime = LocalDateTime.now();

    testAppointment1.setAvailability(Availability.ARRANGED);
    testAppointment1.setTutor(TestUtility.testUser);
    testAppointment1.setStudent(TestUtility.testUserTwo);
    testAppointment1.setWage(BigDecimal.TEN);
    testAppointment1.setDay(dateTime.getDayOfWeek());
    testAppointment1.setTimestamp(Timestamp.valueOf(dateTime));

    appointmentDao.save(testAppointment1);

    testAppointment2.setAvailability(Availability.ARRANGED);
    testAppointment2.setTutor(TestUtility.testUser);
    testAppointment2.setStudent(TestUtility.testUserTwo);
    testAppointment2.setWage(BigDecimal.TEN);
    testAppointment2.setDay(dateTime.getDayOfWeek());
    testAppointment2.setTimestamp(Timestamp.valueOf(dateTime.minusHours(1)));

    appointmentDao.save(testAppointment2);

    BigDecimal reference = BigDecimal.TEN.multiply(ConstantVariables.PERCENTAGE);
    reference = reference.add(BigDecimal.TEN.multiply(ConstantVariables.PERCENTAGE));

    mockMvc
        .perform(get("/bill").principal(this.authUser))
        .andExpect(model().attribute("balance", reference.setScale(2)));
  }
  private void switchCurrency() {
    int newDecimalPlaces;
    BigDecimal newAmount;
    if (_enterFiatAmount) {
      // We are switching from Fiat to BTC

      // Set BTC button
      Button btCurrency = (Button) findViewById(R.id.btCurrency);
      btCurrency.setText(_mbwManager.getBitcoinDenomination().getUnicodeName());

      // Set BTC balance
      ((TextView) findViewById(R.id.tvMaxAmount)).setText(getBalanceString(_balance));

      newDecimalPlaces = _mbwManager.getBitcoinDenomination().getDecimalPlaces();
      Long satoshis = getSatoshisToSend();
      if (satoshis == null) {
        newAmount = null;
      } else {
        newAmount = BigDecimal.valueOf(satoshis).divide(BigDecimal.TEN.pow(newDecimalPlaces));
      }
    } else {
      // We are switching from BTC to Fiat

      // Set Fiat button
      Button btCurrency = (Button) findViewById(R.id.btCurrency);
      btCurrency.setText(_mbwManager.getFiatCurrency());

      // Set Fiat balance
      String fiatBalance = Utils.getFiatValueAsString(_balance, _oneBtcInFiat);
      String balanceString =
          getResources().getString(R.string.max_fiat, fiatBalance, _mbwManager.getFiatCurrency());
      ((TextView) findViewById(R.id.tvMaxAmount)).setText(balanceString);

      newDecimalPlaces = 2;
      Long fiatCents = getFiatCentsToSend();
      if (fiatCents == null) {
        newAmount = null;
      } else {
        newAmount = BigDecimal.valueOf(fiatCents).divide(BigDecimal.TEN.pow(newDecimalPlaces));
      }
    }
    // Note: Do the boolean switch before updating numberEntry, as there is
    // feedback from numberEntry back to ourselves
    _enterFiatAmount = !_enterFiatAmount;
    _numberEntry.setEntry(newAmount, newDecimalPlaces);

    // Check whether we can enable the paste button
    findViewById(R.id.btPaste).setEnabled(enablePaste());
  }
示例#3
0
 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);
 }
示例#4
0
 public static int getDecimais(final double numero, final int casas) {
   final BigDecimal numeroArredondado =
       BigDecimal.valueOf(numero).setScale(casas, RoundingMode.HALF_UP);
   final BigDecimal decimais =
       numeroArredondado.subtract(BigDecimal.valueOf(numeroArredondado.intValue()));
   return decimais.multiply(BigDecimal.TEN.pow(casas)).intValue();
 }
/** User: dashin Date: 1/18/13 Time: 9:58 PM */
@Service(value = "calculatorService")
public class CalculatorServiceImpl implements CalculatorService {

  private final int TEN = BigDecimal.TEN.intValue();

  @Autowired private final FileAccessSerivce fileAccessSerivce = null;

  @Override
  public float get(long v1) throws ValueNotFoundException {
    float v = fileAccessSerivce.findValue(FILE.F2, v1);
    return v > TEN ? v - TEN : v;
  }

  @Override
  public boolean post(long v2, long v3, long v4) throws ValueNotFoundException {
    boolean isConditionMet = false;
    float f1v3 = fileAccessSerivce.findValue(FILE.F1, v3);
    float value = f1v3 + v2;
    if (f1v3 < TEN) {
      value += TEN;
      isConditionMet = true;
    }
    fileAccessSerivce.putValue(FILE.F2, v4, value);
    return isConditionMet;
  }
}
 /**
  * BigDecimal validation test
  *
  * @throws Exception
  */
 @Test
 public void testValidateBigDecimal() throws Exception {
   Assert.assertTrue(FormDataValidator.validateBigDecimal("0"));
   Assert.assertTrue(FormDataValidator.validateBigDecimal("-1"));
   Assert.assertTrue(FormDataValidator.validateBigDecimal("" + BigDecimal.TEN.toPlainString()));
   Assert.assertFalse(FormDataValidator.validateBigDecimal(null));
   Assert.assertFalse(FormDataValidator.validateBigDecimal(""));
   Assert.assertFalse(FormDataValidator.validateBigDecimal("BigDecimal"));
 }
示例#7
0
 /**
  * Returns the base 10 logarithm of a {@link BigInteger}.
  *
  * @param theValue
  * @return
  */
 public static double log10(final BigInteger theValue) {
   /*
    * log10(x) = (x / (10 ^ len(x))) + len(x)
    * http://ubuntuforums.org/showthread.php?t=1461903
    */
   final int length = theValue.toString().length();
   BigDecimal div = BigDecimal.TEN.pow(length);
   BigDecimal res = new BigDecimal(theValue).divide(div);
   return java.lang.Math.log10(res.doubleValue()) + length;
 }
 private void maximizeAmount() {
   if (_maxSendable == 0) {
     String msg = getResources().getString(R.string.insufficient_funds);
     _toast.setText(msg);
     _toast.show();
   } else {
     if (_enterFiatAmount) {
       switchCurrency();
     }
     int newDecimalPlaces = _mbwManager.getBitcoinDenomination().getDecimalPlaces();
     BigDecimal newAmount =
         BigDecimal.valueOf(_maxSendable).divide(BigDecimal.TEN.pow(newDecimalPlaces));
     _numberEntry.setEntry(newAmount, newDecimalPlaces);
   }
 }
示例#9
0
  /**
   * Gets the grid step.
   *
   * @param lengthInPixels axis length in pixels
   * @param min minimum value
   * @param max maximum value
   * @return rounded value.
   */
  private BigDecimal getGridStep(int lengthInPixels, double min, double max) {
    if (lengthInPixels <= 0) {
      throw new IllegalArgumentException("lengthInPixels must be positive value.");
    }
    if (min >= max) {
      throw new IllegalArgumentException("min must be less than max.");
    }

    double length = Math.abs(max - min);
    double gridStepHint = length / lengthInPixels * axis.getTick().getTickMarkStepHint();

    // gridStepHint --> mantissa * 10 ** exponent
    // e.g. 724.1 --> 7.241 * 10 ** 2
    double mantissa = gridStepHint;
    int exponent = 0;
    if (mantissa < 1) {
      while (mantissa < 1) {
        mantissa *= 10.0;
        exponent--;
      }
    } else {
      while (mantissa >= 10) {
        mantissa /= 10.0;
        exponent++;
      }
    }

    // calculate the grid step with hint.
    BigDecimal gridStep;
    if (mantissa > 7.5) {
      // gridStep = 10.0 * 10 ** exponent
      gridStep = BigDecimal.TEN.multiply(pow(10, exponent));
    } else if (mantissa > 3.5) {
      // gridStep = 5.0 * 10 ** exponent
      gridStep = new BigDecimal(new Double(5).toString()).multiply(pow(10, exponent));
    } else if (mantissa > 1.5) {
      // gridStep = 2.0 * 10 ** exponent
      gridStep = new BigDecimal(new Double(2).toString()).multiply(pow(10, exponent));
    } else {
      // gridStep = 1.0 * 10 ** exponent
      gridStep = pow(10, exponent);
    }
    return gridStep;
  }
 @Test
 public void testRetornoValido() {
   Mockery mockery = new Mockery();
   final HttpServletRequest request = mockery.mock(HttpServletRequest.class);
   mockery.checking(
       new Expectations() {
         {
           one(request).getParameter("vpc_TxnResponseCode");
           will(returnValue("0"));
           one(request).getParameter("vpc_Message");
           will(returnValue("Sucesso"));
           one(request).getParameter("vpc_SecureHash");
           will(returnValue("123456789012345"));
           one(request).getParameter("vpc_Merchant");
           will(returnValue("123456"));
           one(request).getParameter("vpc_Command");
           will(returnValue("command"));
           one(request).getParameter("vpc_MerchTxnRef");
           will(returnValue("123456"));
           one(request).getParameter("vpc_OrderInfo");
           will(returnValue("123456"));
           one(request).getParameter("vpc_Amount");
           will(returnValue("1000"));
           one(request).getParameter("vpc_Card");
           will(returnValue("AE"));
           one(request).getParameter("vpc_AcqResponseCode");
           will(returnValue("00"));
           one(request).getParameter("vpc_TransactionNo");
           will(returnValue("2345678787987980890"));
           one(request).getParameter("vpc_BatchNo");
           will(returnValue("20060115"));
           one(request).getParameter("vpc_ReceiptNo");
           will(returnValue("RP12345"));
           one(request).getParameter("vpc_AuthorizeId");
           will(returnValue("2345678787987980890"));
         }
       });
   AmexAutorizacaoReturn amexAutorizacaoReturn =
       new AmexVerificaRetornoAutorizacao(request).handle();
   Assert.assertEquals(BigDecimal.TEN.setScale(2), amexAutorizacaoReturn.getVpc_Amount());
   Assert.assertEquals(AmexTipoCartao.AMERICA_EXPRESS, amexAutorizacaoReturn.getVpc_Card());
 }
示例#11
0
  public String format(BigDecimal d) {

    if (d == null) d = BigDecimal.ZERO;

    if (this.isBlankWhenZero() && d.compareTo(BigDecimal.ZERO) == 0) return blankWhenZero("0");

    if (sym != null) {
      if (getNumberFormat() != null)
        return suppressLeadingZeros(
            addSign(
                getNumberFormat()
                    .format(
                        d.abs()
                            .setScale(
                                getNumberFormat().getMaximumFractionDigits(), RoundingMode.DOWN)
                            .multiply(BigDecimal.TEN.pow(scale))),
                (d.signum() < 0)));
      else if (sym.type == Constants.STRING) {
        return format(d.abs().toPlainString());
      }
    }

    return d.toString();
  }
示例#12
0
 @Test
 public void testParseBigDec() throws ParseException {
   assertEquals(BigDecimal.TEN, EwsUtilities.parse(BigDecimal.class, BigDecimal.TEN.toString()));
 }
示例#13
0
 @Test
 public void testGetAmount() {
   assertThat(iSOAmount.getAmount(), is(BigDecimal.TEN.setScale(2)));
 }
示例#14
0
 @Before
 public void setUp() throws Exception {
   iSOAmount = new ISOAmount(28, 840, BigDecimal.TEN.setScale(2));
 }
示例#15
0
 @Override
 public Sexp visit(RealExpr e) {
   Sexp numerator = Sexp.fromBigInt(e.value.unscaledValue());
   Sexp denominator = Sexp.fromBigInt(BigDecimal.TEN.pow(e.value.scale()).toBigInteger());
   return new Cons("/", numerator, denominator);
 }
示例#16
0
  /**
   * Formats the specified number and returns a string representation.
   *
   * @param item item
   * @param pics pictures
   * @param ii input info
   * @return picture variables
   * @throws QueryException query exception
   */
  private byte[] format(final ANum item, final Picture[] pics, final InputInfo ii)
      throws QueryException {

    // Rule 1: return results for NaN
    final double d = item.dbl(ii);
    if (Double.isNaN(d)) return nan;

    // Rule 2: check if value if negative (smaller than zero or -0)
    final boolean neg = d < 0 || d == 0 && Double.doubleToLongBits(d) == Long.MIN_VALUE;
    final Picture pic = pics[neg && pics.length == 2 ? 1 : 0];
    final IntList res = new IntList(), intgr = new IntList(), fract = new IntList();
    int exp = 0;

    // Rule 3: percent/permille
    ANum num = item;
    if (pic.pc) num = (ANum) Calc.MULT.ev(num, Int.get(100), ii);
    if (pic.pm) num = (ANum) Calc.MULT.ev(num, Int.get(1000), ii);

    if (Double.isInfinite(num.dbl(ii))) {
      // Rule 4: infinity
      intgr.add(new TokenParser(inf).toArray());
    } else {
      // Rule 5: exponent
      if (pic.minExp != 0 && d != 0) {
        BigDecimal dec = num.dec(ii).abs().stripTrailingZeros();
        int scl = 0;
        if (dec.compareTo(BigDecimal.ONE) >= 0) {
          scl = dec.setScale(0, RoundingMode.HALF_DOWN).precision();
        } else {
          while (dec.compareTo(BigDecimal.ONE) < 0) {
            dec = dec.multiply(BigDecimal.TEN);
            scl--;
          }
          scl++;
        }
        exp = scl - pic.min[0];
        if (exp != 0) {
          final BigDecimal n = BigDecimal.TEN.pow(Math.abs(exp));
          num = (ANum) Calc.MULT.ev(num, Dec.get(exp > 0 ? BigDecimal.ONE.divide(n) : n), ii);
        }
      }
      num = num.round(pic.maxFrac, true).abs();

      // convert positive number to string
      final String s =
          (num instanceof Dbl || num instanceof Flt
                  ? Dec.get(BigDecimal.valueOf(num.dbl(ii)))
                  : num)
              .toString();

      // integer/fractional separator
      final int sep = s.indexOf('.');

      // create integer part
      final int sl = s.length();
      final int il = sep == -1 ? sl : sep;
      for (int i = il; i < pic.min[0]; ++i) intgr.add(zero);
      // fractional number: skip leading 0
      if (!s.startsWith("0.") || pic.min[0] > 0) {
        for (int i = 0; i < il; i++) intgr.add(zero + s.charAt(i) - '0');
      }

      // squeeze in grouping separators
      if (pic.group[0].length == 1 && pic.group[0][0] > 0) {
        // regular pattern with repeating separators
        for (int p = intgr.size() - (neg ? 2 : 1); p > 0; --p) {
          if (p % pic.group[0][0] == 0) intgr.insert(intgr.size() - p, grouping);
        }
      } else {
        // irregular pattern, or no separators at all
        final int gl = pic.group[0].length;
        for (int g = 0; g < gl; ++g) {
          final int pos = intgr.size() - pic.group[0][g];
          if (pos > 0) intgr.insert(pos, grouping);
        }
      }

      // create fractional part
      final int fl = sep == -1 ? 0 : sl - il - 1;
      if (fl != 0) for (int i = sep + 1; i < sl; i++) fract.add(zero + s.charAt(i) - '0');
      for (int i = fl; i < pic.min[1]; ++i) fract.add(zero);

      // squeeze in grouping separators in a reverse manner
      final int ul = fract.size();
      for (int p = pic.group[1].length - 1; p >= 0; p--) {
        final int pos = pic.group[1][p];
        if (pos < ul) fract.insert(pos, grouping);
      }
    }

    // add minus sign
    if (neg && pics.length != 2) res.add(minus);
    // add prefix and integer part
    res.add(pic.prefSuf[0].toArray()).add(intgr.finish());
    // add fractional part
    if (!fract.isEmpty()) res.add(decimal).add(fract.finish());
    // add exponent
    if (pic.minExp != 0) {
      res.add(exponent);
      if (exp < 0) res.add(minus);
      final String s = Integer.toString(Math.abs(exp));
      final int sl = s.length();
      for (int i = sl; i < pic.minExp; i++) res.add(zero);
      for (int i = 0; i < sl; i++) res.add(zero + s.charAt(i) - '0');
    }
    // add suffix
    res.add(pic.prefSuf[1].toArray());
    return new TokenBuilder(res.finish()).finish();
  }