Example usage for java.math BigDecimal signum

List of usage examples for java.math BigDecimal signum

Introduction

In this page you can find the example usage for java.math BigDecimal signum.

Prototype

public int signum() 

Source Link

Document

Returns the signum function of this BigDecimal .

Usage

From source file:jp.co.ctc_g.jse.core.validation.util.Validators.java

protected static boolean isDecimal(BigDecimal number, boolean signed, int precision, int scale) {
    if ((!signed) && (number.signum() < 0)) {
        return false;
    }/*  w  w w . j a va  2s .  c o m*/
    int expectedIntPrecision = precision - scale;
    int actualPrecision = number.precision();
    int actualScale = number.scale();
    int actualIntPrecision = actualPrecision - actualScale;
    return (expectedIntPrecision >= actualIntPrecision && scale >= actualScale);
}

From source file:Main.java

public static BigDecimal log10(BigDecimal b) {
    final int NUM_OF_DIGITS = SCALE + 2;
    // need to add one to get the right number of dp
    //  and then add one again to get the next number
    //  so I can round it correctly.

    MathContext mc = new MathContext(NUM_OF_DIGITS, RoundingMode.HALF_EVEN);
    //special conditions:
    // log(-x) -> exception
    // log(1) == 0 exactly;
    // log of a number lessthan one = -log(1/x)
    if (b.signum() <= 0) {
        throw new ArithmeticException("log of a negative number! (or zero)");
    } else if (b.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else if (b.compareTo(BigDecimal.ONE) < 0) {
        return (log10((BigDecimal.ONE).divide(b, mc))).negate();
    }//from   w w w.  j a va2  s  .c  om

    StringBuilder sb = new StringBuilder();
    //number of digits on the left of the decimal point
    int leftDigits = b.precision() - b.scale();

    //so, the first digits of the log10 are:
    sb.append(leftDigits - 1).append(".");

    //this is the algorithm outlined in the webpage
    int n = 0;
    while (n < NUM_OF_DIGITS) {
        b = (b.movePointLeft(leftDigits - 1)).pow(10, mc);
        leftDigits = b.precision() - b.scale();
        sb.append(leftDigits - 1);
        n++;
    }

    BigDecimal ans = new BigDecimal(sb.toString());

    //Round the number to the correct number of decimal places.
    ans = ans.round(new MathContext(ans.precision() - ans.scale() + SCALE, RoundingMode.HALF_EVEN));
    return ans;
}

From source file:Main.java

public static BigDecimal log10(BigDecimal b) {
    final int NUM_OF_DIGITS = SCALE + 2;
    // need to add one to get the right number of dp
    // and then add one again to get the next number
    // so I can round it correctly.

    MathContext mc = new MathContext(NUM_OF_DIGITS, RoundingMode.HALF_EVEN);
    // special conditions:
    // log(-x) -> exception
    // log(1) == 0 exactly;
    // log of a number lessthan one = -log(1/x)
    if (b.signum() <= 0) {
        throw new ArithmeticException("log of a negative number! (or zero)");
    } else if (b.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else if (b.compareTo(BigDecimal.ONE) < 0) {
        return (log10((BigDecimal.ONE).divide(b, mc))).negate();
    }// w w w . j a  va 2 s. c o m

    StringBuilder sb = new StringBuilder();
    // number of digits on the left of the decimal point
    int leftDigits = b.precision() - b.scale();

    // so, the first digits of the log10 are:
    sb.append(leftDigits - 1).append(".");

    // this is the algorithm outlined in the webpage
    int n = 0;
    while (n < NUM_OF_DIGITS) {
        b = (b.movePointLeft(leftDigits - 1)).pow(10, mc);
        leftDigits = b.precision() - b.scale();
        sb.append(leftDigits - 1);
        n++;
    }

    BigDecimal ans = new BigDecimal(sb.toString());

    // Round the number to the correct number of decimal places.
    ans = ans.round(new MathContext(ans.precision() - ans.scale() + SCALE, RoundingMode.HALF_EVEN));
    return ans;
}

From source file:org.wikidata.wdtk.datamodel.json.jackson.datavalues.JacksonInnerQuantity.java

/**
 * Formats the string output with a leading signum as JSON expects it.
 *
 * @param value/* w w w. ja v a 2 s.c  o  m*/
 * @return
 */
private String bigDecimalToSignedString(BigDecimal value) {
    if (value.signum() < 0) {
        return value.toString();
    } else {
        return "+" + value.toString();
    }
}

From source file:org.osiam.resource_server.storage.helper.NumberPadder.java

/**
 * Removes the offset and padding from a number
 *
 * @param value//from  ww  w  .j  av a 2  s.c om
 *            the padded number as {@link String}
 * @return the number decreased by offset and leading '0's removed
 */
public String unpad(String value) {
    BigDecimal decimalValue = new BigDecimal(value);
    BigDecimal returnDecimalValue = new BigDecimal(decimalValue.toBigInteger().subtract(BIG_OFFSET));
    BigDecimal signum = new BigDecimal(returnDecimalValue.signum());
    BigDecimal fractionalPart = decimalValue.remainder(BigDecimal.ONE).multiply(signum);
    returnDecimalValue = returnDecimalValue.add(fractionalPart);
    return returnDecimalValue.toString();
}

From source file:com.aoindustries.website.clientarea.accounting.MakePaymentNewCardAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, SiteSettings siteSettings, Locale locale, Skin skin,
        AOServConnector aoConn) throws Exception {
    MakePaymentNewCardForm makePaymentNewCardForm = (MakePaymentNewCardForm) form;

    String accounting = makePaymentNewCardForm.getAccounting();
    if (GenericValidator.isBlankOrNull(accounting)) {
        // Redirect back to credit-card-manager it no accounting selected
        return mapping.findForward("make-payment");
    }// w w  w  . j  a  v  a  2 s. c o m

    // Populate the initial details from the selected accounting code or authenticated user
    Business business = aoConn.getBusinesses().get(AccountingCode.valueOf(accounting));
    if (business == null)
        throw new SQLException("Unable to find Business: " + accounting);
    BusinessProfile profile = business.getBusinessProfile();
    if (profile != null) {
        makePaymentNewCardForm
                .setFirstName(AddCreditCardAction.getFirstName(profile.getBillingContact(), locale));
        makePaymentNewCardForm
                .setLastName(AddCreditCardAction.getLastName(profile.getBillingContact(), locale));
        makePaymentNewCardForm.setCompanyName(profile.getName());
        makePaymentNewCardForm.setStreetAddress1(profile.getAddress1());
        makePaymentNewCardForm.setStreetAddress2(profile.getAddress2());
        makePaymentNewCardForm.setCity(profile.getCity());
        makePaymentNewCardForm.setState(profile.getState());
        makePaymentNewCardForm.setPostalCode(profile.getZIP());
        makePaymentNewCardForm.setCountryCode(profile.getCountry().getCode());
    } else {
        BusinessAdministrator thisBA = aoConn.getThisBusinessAdministrator();
        makePaymentNewCardForm.setFirstName(AddCreditCardAction.getFirstName(thisBA.getName(), locale));
        makePaymentNewCardForm.setLastName(AddCreditCardAction.getLastName(thisBA.getName(), locale));
        makePaymentNewCardForm.setStreetAddress1(thisBA.getAddress1());
        makePaymentNewCardForm.setStreetAddress2(thisBA.getAddress2());
        makePaymentNewCardForm.setCity(thisBA.getCity());
        makePaymentNewCardForm.setState(thisBA.getState());
        makePaymentNewCardForm.setPostalCode(thisBA.getZIP());
        makePaymentNewCardForm.setCountryCode(thisBA.getCountry() == null ? "" : thisBA.getCountry().getCode());
    }

    initRequestAttributes(request, getServlet().getServletContext());

    // Prompt for amount of payment defaults to current balance.
    BigDecimal balance = business.getAccountBalance();
    if (balance.signum() > 0) {
        makePaymentNewCardForm.setPaymentAmount(balance.toPlainString());
    } else {
        makePaymentNewCardForm.setPaymentAmount("");
    }

    request.setAttribute("business", business);

    return mapping.findForward("success");
}

From source file:de.metas.ui.web.handlingunits.process.WEBUI_M_ReceiptSchedule_GeneratePlanningHUs_MultiRow.java

private final IAllocationRequest createAllocationRequest(final I_M_ReceiptSchedule rs) {
    // Get Qty/*from w  w w  .j a  v a 2s . c  o m*/
    final BigDecimal qty = receiptScheduleBL.getQtyToMove(rs);
    if (qty == null || qty.signum() <= 0) {
        // nothing to do
        return null;
    }

    final IMutableHUContext huContextInitial = Services.get(IHUContextFactory.class)
            .createMutableHUContextForProcessing(getCtx());
    final IAllocationRequest allocationRequest = AllocationUtils.createAllocationRequestBuilder()
            .setHUContext(huContextInitial).setDateAsToday().setProduct(rs.getM_Product())
            .setQuantity(new Quantity(qty, rs.getC_UOM())).setFromReferencedModel(rs)
            .setForceQtyAllocation(true).create();

    return allocationRequest;
}

From source file:no.abmu.questionnaire.domain.validators.PositiveValueValidator.java

private void validateBigDecimalFieldData(BigDecimalFieldData fieldData, Errors errors) {
    BigDecimal bigDecimalValue = fieldData.getBigDecimalValue();
    if (bigDecimalValue != null && bigDecimalValue.signum() < 0) {
        errors.rejectValue(getFieldName(fieldData), "validation.must.be.positive", "Float value for post "
                + fieldData.getCode() + " is " + bigDecimalValue + " which is less than 0");
        if (logger.isDebugEnabled()) {
            logger.debug("Value [" + bigDecimalValue + "] for field with code=[" + fieldData.getCode()
                    + "] FAILED VALIDATION");
        }// w  ww.jav a2  s . c  om
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Value [" + bigDecimalValue + "] for field with code=[" + fieldData.getCode()
                    + "] validated OK");
        }
    }

}

From source file:org.openvpms.esci.adapter.map.UBLFinancialType.java

/**
 * Gets the value from an amount, verifying the currency.
 *
 * @param amount the amount/*ww  w. ja  va  2s  .com*/
 * @param path   the path to the element for error reporting
 * @return the amount value
 * @throws ESCIAdapterException if the amount isn't present, is invalid, or has a currency the doesn't match that
 *                              expected
 */
protected BigDecimal getAmount(AmountType amount, String path) {
    checkRequired(amount, path);
    checkRequired(amount.getValue(), path);
    CurrencyCodeContentType code = getRequired(amount.getCurrencyID(), path + "@currencyID");
    if (!ObjectUtils.equals(currency, code.value())) {
        ErrorContext context = new ErrorContext(this, path);
        throw new ESCIAdapterException(ESCIAdapterMessages.invalidCurrency(context.getPath(), context.getType(),
                context.getID(), currency, code.value()));
    }
    BigDecimal result = amount.getValue();
    if (result.signum() == -1) {
        ErrorContext context = new ErrorContext(this, path);
        throw new ESCIAdapterException(ESCIAdapterMessages.invalidAmount(context.getPath(), context.getType(),
                context.getID(), result));
    }
    return amount.getValue();
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.CommonSourceConfigBean.java

public RateLimiter creatQueryRateLimiter() {
    final BigDecimal rateLimit = new BigDecimal(queriesPerSecond);
    if (rateLimit.signum() < 1) {
        // negative or zero value; no rate limit
        return null;
    } else {/*from   w ww  .  j av  a2 s.  com*/
        return RateLimiter.create(rateLimit.doubleValue());
    }
}