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:org.cirdles.geoapp.LatLongToUTM.java

private static int calcZoneNumber(BigDecimal longitude) {
    int zoneNumber;
    BigDecimal six = new BigDecimal(6);

    if (longitude.signum() < 0) {

        BigDecimal oneEighty = new BigDecimal(180);
        zoneNumber = ((oneEighty.add(longitude)).divide(six, precision, RoundingMode.HALF_UP)).intValue() + 1;
    }/* w ww  .  j  av  a 2s.co m*/

    else {

        BigDecimal thirtyOne = new BigDecimal(31);
        zoneNumber = ((longitude.divide(six, precision, RoundingMode.HALF_UP)).abs().add(thirtyOne)).intValue();
    }

    return zoneNumber;

}

From source file:org.cirdles.geoapp.LatLongToUTM.java

private static BigDecimal calcNorthing(BigDecimal meridianRadius, BigDecimal xiNorth, BigDecimal latitude) {

    BigDecimal northing = (scaleFactor.multiply(meridianRadius)).multiply(xiNorth);

    if (latitude.signum() < 0)
        northing = southHemisphereSubtraction.subtract(northing);

    return northing;

}

From source file:org.openbravo.costing.PriceDifferenceProcess.java

private static boolean calculateTransactionPriceDifferenceLogic(MaterialTransaction materialTransaction)
        throws OBException {
    boolean costAdjCreated = false;

    // With Standard Algorithm, no cost adjustment is needed
    if (StringUtils.equals(materialTransaction.getCostingAlgorithm().getJavaClassName(),
            "org.openbravo.costing.StandardAlgorithm")) {
        return false;
    }//from w  ww.ja  v a  2  s.  c om

    if (materialTransaction.isCostPermanent()) {
        // Permanently adjusted transaction costs are not checked for price differences.
        return false;
    }
    Currency trxCurrency = materialTransaction.getCurrency();
    Organization trxOrg = materialTransaction.getOrganization();
    Date trxDate = materialTransaction.getMovementDate();
    int costCurPrecission = trxCurrency.getCostingPrecision().intValue();
    ShipmentInOutLine receiptLine = materialTransaction.getGoodsShipmentLine();
    if (receiptLine == null
            || !isValidPriceAdjTrx(receiptLine.getMaterialMgmtMaterialTransactionList().get(0))) {
        // We can only adjust cost of receipt lines.
        return false;
    }

    BigDecimal receiptQty = receiptLine.getMovementQuantity();
    boolean isNegativeReceipt = receiptQty.signum() == -1;
    if (isNegativeReceipt) {
        // If the receipt is negative convert the quantity to positive.
        receiptQty = receiptQty.negate();
    }

    Date costAdjDateAcct = null;
    BigDecimal invoiceAmt = BigDecimal.ZERO;

    // Calculate current transaction unit cost including existing adjustments.
    BigDecimal currentTrxUnitCost = CostAdjustmentUtils.getTrxCost(materialTransaction, true, trxCurrency);

    // Calculate expected transaction unit cost based on current invoice amounts and purchase price.
    BigDecimal expectedCost = BigDecimal.ZERO;
    BigDecimal invoiceQty = BigDecimal.ZERO;
    for (ReceiptInvoiceMatch matchInv : receiptLine.getProcurementReceiptInvoiceMatchList()) {
        Invoice invoice = matchInv.getInvoiceLine().getInvoice();
        if (invoice.getDocumentStatus().equals("VO")) {
            // Skip voided invoices.
            continue;
        }
        if (!invoice.isProcessed()) {
            // Skip not processed invoices.
            continue;
        }
        if (isNegativeReceipt) {
            // If the receipt is negative negate the invoiced quantities.
            invoiceQty = invoiceQty.add(matchInv.getQuantity().negate());
        } else {
            invoiceQty = invoiceQty.add(matchInv.getQuantity());
        }
        invoiceAmt = matchInv.getQuantity().multiply(matchInv.getInvoiceLine().getUnitPrice());

        invoiceAmt = FinancialUtils.getConvertedAmount(invoiceAmt, invoice.getCurrency(), trxCurrency, trxDate,
                trxOrg, FinancialUtils.PRECISION_STANDARD, invoice.getCurrencyConversionRateDocList());
        expectedCost = expectedCost.add(invoiceAmt);

        Date invoiceDate = invoice.getInvoiceDate();
        if (costAdjDateAcct == null || costAdjDateAcct.before(invoiceDate)) {
            costAdjDateAcct = invoiceDate;
        }
    }

    BigDecimal notInvoicedQty = receiptQty.subtract(invoiceQty);
    if (notInvoicedQty.signum() > 0) {
        // Not all the receipt line is invoiced, add pending invoice quantity valued with current
        // order price if exists or original unit cost.
        BigDecimal basePrice = BigDecimal.ZERO;
        Currency baseCurrency = trxCurrency;
        if (receiptLine.getSalesOrderLine() != null) {
            basePrice = receiptLine.getSalesOrderLine().getUnitPrice();
            baseCurrency = receiptLine.getSalesOrderLine().getSalesOrder().getCurrency();
        } else {
            basePrice = materialTransaction.getTransactionCost().divide(receiptQty, costCurPrecission,
                    RoundingMode.HALF_UP);
        }
        BigDecimal baseAmt = notInvoicedQty.multiply(basePrice).setScale(costCurPrecission,
                RoundingMode.HALF_UP);
        if (!baseCurrency.getId().equals(trxCurrency.getId())) {
            baseAmt = FinancialUtils.getConvertedAmount(baseAmt, baseCurrency, trxCurrency, trxDate, trxOrg,
                    FinancialUtils.PRECISION_STANDARD);
        }
        expectedCost = expectedCost.add(baseAmt);
    }
    // if the sum of trx costs with flag "isInvoiceCorrection" is distinct that the amount cost
    // generated by Match Invoice then New Cost Adjustment line is created by the difference
    if (expectedCost.compareTo(currentTrxUnitCost) != 0) {
        if (costAdjDateAcct == null) {
            costAdjDateAcct = trxDate;
        }
        createCostAdjustmenHeader(trxOrg);
        CostAdjustmentLine costAdjLine = CostAdjustmentUtils.insertCostAdjustmentLine(materialTransaction,
                costAdjHeader, expectedCost.subtract(currentTrxUnitCost), Boolean.TRUE, costAdjDateAcct);
        costAdjLine.setNeedsPosting(Boolean.TRUE);
        OBDal.getInstance().save(costAdjLine);
        costAdjCreated = true;
    }

    return costAdjCreated;
}

From source file:org.cirdles.ambapo.LatLongToUTM.java

/**
 * Returns whether the latitude indicates being in the southern or northern
 * hemisphere. /* ww w .j  av a 2s .  co  m*/
 * @param latitude
 * @return char Hemisphere
 */
private static char calcHemisphere(BigDecimal latitude) {

    char hemisphere = 'N';

    if (latitude.signum() == -1)
        hemisphere = 'S';

    return hemisphere;
}

From source file:org.cirdles.ambapo.LatLongToUTM.java

/**
 * Returns the zone number that the longitude corresponds to on the UTM map
 * //  w  w  w  . j a  v  a  2s  . c om
 * @param longitude
 * @return int zone number
 * 
 * 
 */
private static int calcZoneNumber(BigDecimal longitude) {
    int zoneNumber;
    BigDecimal six = new BigDecimal(6);

    if (longitude.signum() < 0) {

        BigDecimal oneEighty = new BigDecimal(180);
        zoneNumber = ((oneEighty.add(longitude)).divide(six, PRECISION, RoundingMode.HALF_UP)).intValue() + 1;
    }

    else {

        BigDecimal thirtyOne = new BigDecimal(31);
        zoneNumber = ((longitude.divide(six, PRECISION, RoundingMode.HALF_UP)).abs().add(thirtyOne)).intValue();
    }

    if (zoneNumber > 60)
        zoneNumber = 60;

    if (zoneNumber < 1)
        zoneNumber = 1;

    return zoneNumber;

}

From source file:org.cirdles.ambapo.LatLongToUTM.java

/**
 * UTM northing coordinates are measured relative to the equator
 * For locations north of the equator the equator is assigned the northing 
 * value of 0 meters North//from   w  ww .jav  a2s .  c  om
 * To avoid negative numbers, locations south of the equator are made with 
 * the equator assigned a value of 10,000,000 meters North.
 * @param meridianRadius
 * @param xiNorth
 * @param latitude
 * @return BigDecimal northing
 */
private static BigDecimal calcNorthing(BigDecimal meridianRadius, BigDecimal xiNorth, BigDecimal latitude) {

    BigDecimal northing = (SCALE_FACTOR.multiply(meridianRadius)).multiply(xiNorth);

    if (latitude.signum() < 0)
        northing = SOUTH_HEMISPHERE_SUBTRACTION.subtract(northing);

    return northing;

}

From source file:org.jpox.util.SQLFormat.java

/**
     * Formats the given BigDecimal value into a SQL floating-point literal.
     * BigDecimal.toString() is not well suited to this purpose because it never
     * uses E-notation, which causes some values with large exponents to be
     * output as long strings with tons of zeroes in them.
     *//  www  .  java 2s .  c om
     * @param bd  The number to format.
     *
     * @return  The formatted String.
     */
    public static String format(BigDecimal bd) {
        String digits = bd.unscaledValue().abs().toString();
        int scale = bd.scale();
        int len = digits.length();

        /* Normalize by removing any trailing zeroes. */
        while (len > 1 && digits.charAt(len - 1) == '0') {
            --scale;
            --len;
        }

        if (len < digits.length()) {
            digits = digits.substring(0, len);
        }

        StringBuffer sb = new StringBuffer();

        if (bd.signum() < 0) {
            sb.append('-');
        }

        int exponent = len - scale;

        if (exponent < 0 || exponent > len) {
            /* Output in E-notation. */
            sb.append('.').append(digits).append('E').append(exponent);
        } else if (exponent == len) {
            /* Output as an integer. */
            sb.append(digits);
        } else {
            /* Output as "intDigits.fracDigits". */
            sb.append(digits.substring(0, exponent)).append('.').append(digits.substring(exponent));
        }

        return sb.toString();
    }

From source file:org.openbravo.financial.FinancialUtils.java

/**
 * Converts an amount./*from w  w  w.ja va2s  . c  om*/
 * 
 * @param amount
 *          BigDecimal amount to convert.
 * @param curFrom
 *          Currency to convert from.
 * @param curTo
 *          Currency to convert to.
 * @param date
 *          Date conversion is being performed.
 * @param org
 *          Organization of the document that needs to be converted.
 * @param strPrecision
 *          type of precision to be used to round the converted amount.
 * @param rateDocs
 *          list of conversion rates defined on the document of the amount that needs to be
 *          converted.
 * @return a BigDecimal representing the converted amount.
 * @throws OBException
 *           when no Conversion Rate is found for the given parameters.
 */
public static BigDecimal getConvertedAmount(BigDecimal amount, Currency curFrom, Currency curTo, Date date,
        Organization org, String strPrecision, List<ConversionRateDoc> rateDocs) throws OBException {
    Check.isNotNull(rateDocs, OBMessageUtils.messageBD("ParameterMissing") + " (rateDocs)");
    if (curFrom.getId().equals(curTo.getId()) || amount.signum() == 0) {
        return amount;
    }
    BigDecimal rate = null;
    if (rateDocs.size() > 0) {
        for (ConversionRateDoc rateDoc : rateDocs) {
            if (curFrom.getId().equals(rateDoc.getCurrency().getId())
                    && curTo.getId().equals(rateDoc.getToCurrency().getId())) {
                rate = rateDoc.getRate();
                break;
            }
        }
    }
    if (rate == null) {
        ConversionRate cr = getConversionRate(date, curFrom, curTo, org, org.getClient());
        if (cr == null) {
            throw new OBException("@NoCurrencyConversion@ " + curFrom.getISOCode() + " @to@ "
                    + curTo.getISOCode() + " @ForDate@ " + OBDateUtils.formatDate(date)
                    + " @And@ @ACCS_AD_ORG_ID_D@ " + org.getIdentifier());
        }
        rate = cr.getMultipleRateBy();
    }
    Long precision = curTo.getStandardPrecision();
    if (PRECISION_COSTING.equals(strPrecision)) {
        precision = curTo.getCostingPrecision();
    } else if (PRECISION_PRICE.equals(strPrecision)) {
        precision = curTo.getPricePrecision();
    }
    return amount.multiply(rate).setScale(precision.intValue(), RoundingMode.HALF_UP);
}

From source file:org.libreplan.business.planner.entities.StretchesFunction.java

public static List<Interval> intervalsFor(ResourceAllocation<?> allocation,
        Collection<? extends Stretch> stretches) {

    ArrayList<Interval> result = new ArrayList<>();
    LocalDate previous = null;/*from   w w  w. j a  v  a  2s. co m*/
    LocalDate stretchDate;

    BigDecimal sumOfProportions = BigDecimal.ZERO;
    BigDecimal loadedProportion;

    for (Stretch each : stretches) {
        stretchDate = each.getDateIn(allocation);
        loadedProportion = each.getAmountWorkPercentage().subtract(sumOfProportions);

        if (loadedProportion.signum() < 0) {
            loadedProportion = BigDecimal.ZERO;
        }

        result.add(Interval.create(loadedProportion, previous, stretchDate, each.isConsolidated()));
        sumOfProportions = each.getAmountWorkPercentage();
        previous = stretchDate;
    }

    return result;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

public static String getPartitionSizeValidationError(int colType, String column, String partitionSize) {
    switch (colType) {
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        try {//from   w ww .j  av  a  2s.c om
            int intVal = Integer.parseInt(partitionSize);
            if (intVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.BIGINT:
        // TIME, DATE, and TIMESTAMP are represented as long (epoch)
    case Types.TIME:
    case Types.DATE:
    case Types.TIMESTAMP:
        try {
            long longVal = Long.parseLong(partitionSize);
            if (longVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.FLOAT:
    case Types.REAL:
        try {
            float floatVal = Float.parseFloat(partitionSize);
            if (floatVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.DOUBLE:
        try {
            double doubleVal = Double.parseDouble(partitionSize);
            if (doubleVal <= 0) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    case Types.NUMERIC:
    case Types.DECIMAL:
        try {
            BigDecimal decimalValue = new BigDecimal(partitionSize);
            if (decimalValue.signum() < 1) {
                return createPartitionSizeValidationError(column, partitionSize, colType,
                        GENERIC_PARTITION_SIZE_GT_ZERO_MSG);
            }
        } catch (NumberFormatException e) {
            return createPartitionSizeValidationError(column, partitionSize, colType, e.getMessage());
        }
        break;
    }
    return null;
}