Java Code Examples for java.math.BigDecimal#setScale()

The following examples show how to use java.math.BigDecimal#setScale() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Calculate azimuth of a ray
 *
 * @param az0 azimuth at beginning of ray (binary angle)
 * @param az1 azimuth at end of ray (binary angle)
 * @return float azimuth in degrees with precision of two decimal
 */
static float calcAz(short az0, short az1) {
  // output in deg
  float azim0 = calcAngle(az0);
  float azim1 = calcAngle(az1);
  float d;
  d = Math.abs(azim0 - azim1);
  if ((az0 < 0) & (az1 > 0)) {
    d = Math.abs(360.0f - azim0) + Math.abs(azim1);
  }
  double temp = azim0 + d * 0.5;
  if (temp > 360.0) {
    temp -= 360.0;
  }
  BigDecimal bd = new BigDecimal(temp);
  BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN);
  return result.floatValue();
}
 
Example 2
Source Project: gemfirexd-oss   File: RawStoreResultSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public BigDecimal getBigDecimal(int columnIndex, int scale)
    throws SQLException {
  BigDecimal ret = getBigDecimal(columnIndex);
  if (ret != null) {
    return ret.setScale(scale, BigDecimal.ROUND_HALF_DOWN);
  }
  return null;
}
 
Example 3
/**
 * Calculate radial elevation of each ray
 *
 * @param angle two bytes binary angle
 * @return float value of elevation in degrees with precision of two decimal
 */
static float calcElev(short angle) {
  double maxval = 65536.0;
  double ang = (double) angle;
  if (angle < 0)
    ang = (~angle) + 1;
  double temp = (ang / maxval) * 360.0;
  BigDecimal bd = new BigDecimal(temp);
  BigDecimal result = bd.setScale(2, RoundingMode.HALF_DOWN);
  return result.floatValue();
}
 
Example 4
Source Project: openjdk-systemtest   File: TestSuite063.java    License: Apache License 2.0 5 votes vote down vote up
public void testItem_0031()
{
    BigDecimal alpha = new BigDecimal("1000").setScale(0);
    BigDecimal beta = new BigDecimal("0.70").setScale(2);
    BigDecimal gamma = alpha.divide(beta, BigDecimal.ROUND_DOWN);
    gamma.setScale(2);
    Assert.assertEquals("1428", gamma.toString());
}
 
Example 5
Source Project: pagseguro_android   File: PagSeguroItem.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a new pagseguro product item.
 * @param id the product's id with max length of 100 characters
 * @param description the product's description with max length of 100 characters
 * @param amount the prodtuct's price with 2 decimals greater 0 and max 9999999.00
 * @param quantity the number of units purchased greater 0 and max 999
 * @param weightInGramms the gross product's weight in grams greater 0 and max. 1000*30 (30kg)
 */
public PagSeguroItem(@NonNull final String id, @NonNull final String description, @NonNull final BigDecimal amount, @NonNull final int quantity, @NonNull final int weightInGramms) {
    validate(id, description, amount, quantity, weightInGramms);
    this.id = id;
    this.description = description;
    this.amount = amount.setScale(2, BigDecimal.ROUND_FLOOR);
    this.quantity = quantity;
    this.weightInGramms = weightInGramms;
}
 
Example 6
/**
 * Adjust the result value by apply the scale, if appropriate.
 */
private BigDecimal adjustResult(BigDecimal d) {
    if (this.hasScale) {
        try {
            return d.setScale(this.scale);
        } catch (ArithmeticException ex) {
            // try this if above fails
            return d.setScale(this.scale, BigDecimal.ROUND_HALF_UP);
        }
    }

    return d;
}
 
Example 7
Source Project: openjdk-systemtest   File: TestSuite063.java    License: Apache License 2.0 5 votes vote down vote up
public void testItem_0056()
{
    BigDecimal alpha = new BigDecimal("1000");
    BigDecimal beta = new BigDecimal("0.70");
    BigDecimal gamma = alpha.divide(beta, BigDecimal.ROUND_DOWN);
    gamma.setScale(2, BigDecimal.ROUND_DOWN);
    Assert.assertEquals("1428", gamma.toString());
}
 
Example 8
public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}
 
Example 9
/**
   Creates a fixed decimal instance by parsing the specified string.

   @param s a string on the same format accepted by {@link Decimal}
   @param scale a scale
   @return a fixed decimal value
*/

public static FixedDec valueOf (String s, int scale)
{
   BigDecimal bd = new BigDecimal (s);
   int fromScale = bd.scale ();
   if (fromScale < 0)
   {
      bd = bd.setScale (0);
      fromScale = 0;
   }

   return valueOf (bd.unscaledValue ().longValue (), fromScale, scale);
}
 
Example 10
@Override
public PointsPossibleValidation isPointsPossibleValid(final String gradebookUid,
		final org.sakaiproject.service.gradebook.shared.Assignment gradebookItem,
		final Double pointsPossible) {
	if (gradebookUid == null) {
		throw new IllegalArgumentException("Null gradebookUid passed to isPointsPossibleValid");
	}
	if (gradebookItem == null) {
		throw new IllegalArgumentException("Null gradebookItem passed to isPointsPossibleValid");
	}

	// At this time, all gradebook items follow the same business rules for
	// points possible (aka relative weight in % gradebooks) so special logic
	// using the properties of the gradebook item is unnecessary.
	// In the future, we will have the flexibility to change
	// that behavior without changing the method signature

	// the points possible must be a non-null value greater than 0 with
	// no more than 2 decimal places

	if (pointsPossible == null) {
		return PointsPossibleValidation.INVALID_NULL_VALUE;
	}

	if (pointsPossible <= 0) {
		return PointsPossibleValidation.INVALID_NUMERIC_VALUE;
	}
	// ensure there are no more than 2 decimal places
	BigDecimal bd = new BigDecimal(pointsPossible);
	bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); // Two decimal places
	final double roundedVal = bd.doubleValue();
	final double diff = pointsPossible - roundedVal;
	if (diff != 0) {
		return PointsPossibleValidation.INVALID_DECIMAL;
	}

	return PointsPossibleValidation.VALID;
}
 
Example 11
Source Project: openjdk-systemtest   File: TestSuite063.java    License: Apache License 2.0 5 votes vote down vote up
public void testItem_0025()
{
    BigDecimal alpha = new BigDecimal(new BigInteger("1000"), 0);
    BigDecimal beta = new BigDecimal(new BigInteger("70"), 2);
    BigDecimal gamma = alpha.subtract(beta);
    gamma.setScale(2);
    Assert.assertEquals("999.30", gamma.toString());
}
 
Example 12
/**
 * Permet de créer une réconciliation en passant les paramètres qu'il faut
 *
 * @param lineDebit Une ligne d'écriture au débit
 * @param lineCredit Une ligne d'écriture au crédit
 * @param amount Le montant à reconciler
 * @param canBeZeroBalanceOk Peut être soldé?
 * @return Une reconciliation
 */
@Transactional
public Reconcile createReconcile(
    MoveLine debitMoveLine,
    MoveLine creditMoveLine,
    BigDecimal amount,
    boolean canBeZeroBalanceOk) {

  if (ReconcileService.isReconcilable(debitMoveLine, creditMoveLine)
      && amount.compareTo(BigDecimal.ZERO) > 0) {
    log.debug(
        "Create Reconcile (Company : {}, Debit MoveLine : {}, Credit MoveLine : {}, Amount : {}, Can be zero balance ? {} )",
        debitMoveLine.getMove().getCompany(),
        debitMoveLine.getName(),
        creditMoveLine.getName(),
        amount,
        canBeZeroBalanceOk);

    Reconcile reconcile =
        new Reconcile(
            debitMoveLine.getMove().getCompany(),
            amount.setScale(2, RoundingMode.HALF_EVEN),
            debitMoveLine,
            creditMoveLine,
            ReconcileRepository.STATUS_DRAFT,
            canBeZeroBalanceOk);

    if (!moveToolService.isDebitMoveLine(debitMoveLine)) {

      reconcile.setDebitMoveLine(creditMoveLine);
      reconcile.setCreditMoveLine(debitMoveLine);
    }

    return reconcileRepository.save(reconcile);
  }
  return null;
}
 
Example 13
/**
     * 申请提币(添加验证码校验)
     * @param user
     * @param unit
     * @param address
     * @param amount
     * @param fee
     * @param remark
     * @param jyPassword
     * @return
     * @throws Exception
     */
    @RequestMapping("apply/code")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult withdrawCode(@SessionAttribute(SESSION_MEMBER) AuthMember user, String unit, String address,
                                  BigDecimal amount, BigDecimal fee,String remark,String jyPassword,@RequestParam("code") String code) throws Exception {
        hasText(jyPassword, sourceService.getMessage("MISSING_JYPASSWORD"));
        hasText(unit, sourceService.getMessage("MISSING_COIN_TYPE"));
        Coin coin = coinService.findByUnit(unit);
        amount.setScale(coin.getWithdrawScale(),BigDecimal.ROUND_DOWN);
        notNull(coin, sourceService.getMessage("COIN_ILLEGAL"));

        isTrue(coin.getStatus().equals(CommonStatus.NORMAL) && coin.getCanWithdraw().equals(BooleanEnum.IS_TRUE), sourceService.getMessage("COIN_NOT_SUPPORT"));
        isTrue(compare(fee, new BigDecimal(String.valueOf(coin.getMinTxFee()))), sourceService.getMessage("CHARGE_MIN") + coin.getMinTxFee());
        isTrue(compare(new BigDecimal(String.valueOf(coin.getMaxTxFee())), fee), sourceService.getMessage("CHARGE_MAX") + coin.getMaxTxFee());
        isTrue(compare(coin.getMaxWithdrawAmount(), amount), sourceService.getMessage("WITHDRAW_MAX") + coin.getMaxWithdrawAmount());
        isTrue(compare(amount, coin.getMinWithdrawAmount()), sourceService.getMessage("WITHDRAW_MIN") + coin.getMinWithdrawAmount());
        MemberWallet memberWallet = memberWalletService.findByCoinAndMemberId(coin, user.getId());
        isTrue(compare(memberWallet.getBalance(), amount), sourceService.getMessage("INSUFFICIENT_BALANCE"));
//        isTrue(memberAddressService.findByMemberIdAndAddress(user.getId(), address).size() > 0, sourceService.getMessage("WRONG_ADDRESS"));
        isTrue(memberWallet.getIsLock()==BooleanEnum.IS_FALSE,"钱包已锁定");
        Member member = memberService.findOne(user.getId());
        String mbPassword = member.getJyPassword();
        Assert.hasText(mbPassword, sourceService.getMessage("NO_SET_JYPASSWORD"));
        Assert.isTrue(Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword), sourceService.getMessage("ERROR_JYPASSWORD"));
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String phone= member.getMobilePhone();
        Object codeRedis =valueOperations.get(SysConstant.PHONE_WITHDRAW_MONEY_CODE_PREFIX + phone);
        notNull(codeRedis, sourceService.getMessage("VERIFICATION_CODE_NOT_EXISTS"));
        if (!codeRedis.toString().equals(code)) {
            return error(sourceService.getMessage("VERIFICATION_CODE_INCORRECT"));
        } else {
            valueOperations.getOperations().delete(SysConstant.PHONE_WITHDRAW_MONEY_CODE_PREFIX + phone);
        }
        MessageResult result = memberWalletService.freezeBalance(memberWallet, amount);
        if (result.getCode() != 0) {
            throw new InformationExpiredException("Information Expired");
        }
        WithdrawRecord withdrawApply = new WithdrawRecord();
        withdrawApply.setCoin(coin);
        withdrawApply.setFee(fee);
        withdrawApply.setArrivedAmount(sub(amount, fee));
        withdrawApply.setMemberId(user.getId());
        withdrawApply.setTotalAmount(amount);
        withdrawApply.setAddress(address);
        withdrawApply.setRemark(remark);
        withdrawApply.setCanAutoWithdraw(coin.getCanAutoWithdraw());

        //提币数量低于或等于阈值并且该币种支持自动提币
        if (amount.compareTo(coin.getWithdrawThreshold()) <= 0 && coin.getCanAutoWithdraw().equals(BooleanEnum.IS_TRUE)) {
            withdrawApply.setStatus(WithdrawStatus.WAITING);
            withdrawApply.setIsAuto(BooleanEnum.IS_TRUE);
            withdrawApply.setDealTime(withdrawApply.getCreateTime());
            WithdrawRecord withdrawRecord = withdrawApplyService.save(withdrawApply);
            JSONObject json = new JSONObject();
            json.put("uid", user.getId());
            //提币总数量
            json.put("totalAmount", amount);
            //手续费
            json.put("fee", fee);
            //预计到账数量
            json.put("arriveAmount", sub(amount, fee));
            //币种
            json.put("coin", coin);
            //提币地址
            json.put("address", address);
            //提币记录id
            json.put("withdrawId", withdrawRecord.getId());
            kafkaTemplate.send("withdraw", coin.getUnit(), json.toJSONString());
            return MessageResult.success(sourceService.getMessage("APPLY_SUCCESS"));
        } else {
            withdrawApply.setStatus(WithdrawStatus.PROCESSING);
            withdrawApply.setIsAuto(BooleanEnum.IS_FALSE);
            if (withdrawApplyService.save(withdrawApply) != null) {
                return MessageResult.success(sourceService.getMessage("APPLY_AUDIT"));
            } else {
                throw new InformationExpiredException("Information Expired");
            }
        }
    }
 
Example 14
Source Project: developerWorks   File: SeasonData.java    License: Apache License 2.0 4 votes vote down vote up
public void setScoringMarginPerGame(BigDecimal scoringMarginPerGame) {
  this.scoringMarginPerGame = scoringMarginPerGame.setScale(StatsUtils.SCALE, RoundingMode.HALF_UP);
}
 
Example 15
Source Project: tutorials   File: RemovingDecimalsManualTest.java    License: MIT License 4 votes vote down vote up
@Benchmark
public String whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
    BigDecimal big = new BigDecimal(doubleValue);
    big = big.setScale(0, RoundingMode.FLOOR);
    return big.toString();
}
 
Example 16
public MonetaryAmount multiply(BigDecimal multiplier, RoundingMode rounding) {
    BigDecimal multiplication = amount.multiply(multiplier);
    return new MonetaryAmount(multiplication.setScale(2, rounding));
}
 
Example 17
Source Project: cloudstack   File: QuotaSummaryResponse.java    License: Apache License 2.0 4 votes vote down vote up
public void setQuotaUsage(BigDecimal startQuota) {
    this.quotaUsage = startQuota.setScale(2, RoundingMode.HALF_EVEN);
}
 
Example 18
Source Project: live-chat-engine   File: TariffMath.java    License: Apache License 2.0 4 votes vote down vote up
public static BigDecimal round(BigDecimal val){
	return val.setScale(2, BigDecimal.ROUND_HALF_UP);
}
 
Example 19
/**
 * Compute the integral root of x to a given scale, x >= 0. Use Newton's
 * algorithm.
 * 
 * @param x
 *            the value of x
 * @param index
 *            the integral root value
 * @param scale
 *            the desired scale of the result
 * @return the result value
 */
public static BigDecimal intRoot(BigDecimal x, BigInteger index, int scale) {
	// Check that x >= 0.
	if (x.signum() < 0) {
		throw new ArithmeticException("x < 0");
	}

	int sp1 = scale + 1;
	BigDecimal n = x;
	BigDecimal i = new BigDecimal(index);
	BigDecimal im1 = i.subtract(BigDecimal.ONE);
	BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);
	BigDecimal xPrev;
	BigInteger indexm1 = index.subtract(BigInteger.ONE);

	// The initial approximation is x/index.
	x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN);

	// Loop until the approximations converge
	// (two successive approximations are equal after rounding).
	do {
		// x^(index-1)
		BigDecimal xToIm1 = intPower(x, indexm1, sp1 + 1);
		// x^index
		BigDecimal xToI = x.multiply(xToIm1);
		// n + (index-1)*(x^index)
		BigDecimal numerator = n.add(im1.multiply(xToI));
		// (index*(x^(index-1))
		BigDecimal denominator = i.multiply(xToIm1);
		// x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
		xPrev = x;
		if (denominator.compareTo(BigDecimal.ZERO) == 0) {
			x = BigDecimal.ZERO.setScale(sp1);
		}
		else {
			x = numerator.divide(denominator, sp1, BigDecimal.ROUND_DOWN);
		}

	} while (x.subtract(xPrev).abs().compareTo(tolerance) > 0);

	return x.setScale(scale, RoundingMode.HALF_EVEN);
}
 
Example 20
Source Project: jsr354-ri   File: ConvertMinorPartQuery.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Gets the amount in minor units as a {@code long}.
 * <p>
 * This returns the monetary amount in terms of the minor units of the
 * currency, truncating the amount if necessary. For example, 'EUR 2.35'
 * will return 235, and 'BHD -1.345' will return -1345.
 * <p>
 * This method matches the API of {@link java.math.BigDecimal}.
 *
 * @return the minor units part of the amount
 * @throws ArithmeticException
 *             if the amount is too large for a {@code long}
 */
@Override
public Long queryFrom(MonetaryAmount amount) {
	Objects.requireNonNull(amount, "Amount required.");
	BigDecimal number = amount.getNumber().numberValue(BigDecimal.class);
	CurrencyUnit cur = amount.getCurrency();
	int scale = cur.getDefaultFractionDigits();
	if(scale<0){
		scale = 0;
	}
	number = number.setScale(scale, RoundingMode.DOWN);
	return number.movePointRight(number.scale()).longValueExact();
}