Example usage for java.math BigDecimal remainder

List of usage examples for java.math BigDecimal remainder

Introduction

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

Prototype

public BigDecimal remainder(BigDecimal divisor) 

Source Link

Document

Returns a BigDecimal whose value is (this % divisor) .

Usage

From source file:Main.java

public static void main(String[] args) {

    BigDecimal bg1 = new BigDecimal("513.54");
    BigDecimal bg2 = new BigDecimal("5");

    // bg2 divided by bg1 gives bg3 as remainder
    BigDecimal bg3 = bg1.remainder(bg2);

    String str = "The remainder is " + bg3;

    // print the value of bg3
    System.out.println(str);//w  w w .j a va  2  s  .c  o  m
}

From source file:MainClass.java

public static void main(String argv[]) {
    BigDecimal first = new BigDecimal("3419229223372036854775807.23343");
    BigDecimal second = new BigDecimal("2.0");
    System.out.println(first.add(second));
    System.out.println(first.subtract(second));
    System.out.println(first.divide(second));
    System.out.println(first.equals(second));
    System.out.println(first.abs());
    System.out.println(first.max(second));
    System.out.println(first.min(second));
    System.out.println(first.remainder(second));
}

From source file:io.curly.advisor.model.Review.java

private BigDecimal fixPrecision(BigDecimal rate) {
    if (rate == null)
        return BigDecimal.ZERO;
    BigDecimal decimal = rate.remainder(BigDecimal.ONE);
    BigInteger integer = rate.toBigInteger();
    if (decimal.compareTo(new BigDecimal(0.5)) > 0) {
        return new BigDecimal(integer.add(new BigInteger("1")));
    } else if (decimal.compareTo(new BigDecimal(0.5)) < 0) {
        return new BigDecimal(integer);
    }/*from www  .ja v a2 s  .c  om*/
    return rate;
}

From source file:org.eel.kitchen.jsonschema.keyword.DivisibleByKeywordValidator.java

@Override
protected void validateDecimal(final ValidationReport report, final JsonNode instance) {
    final BigDecimal instanceValue = instance.decimalValue();
    final BigDecimal decimalValue = number.decimalValue();

    final BigDecimal remainder = instanceValue.remainder(decimalValue);

    /*/*from   ww w  .j a  v a  2s.  c  o m*/
     * We cannot use equality! As far as BigDecimal goes,
     * "0" and "0.0" are NOT equal. But .compareTo() returns the correct
     * result.
     */
    if (remainder.compareTo(BigDecimal.ZERO) == 0)
        return;

    final Message.Builder msg = newMsg().setMessage("number is not a multiple of divisibleBy")
            .addInfo("value", instance).addInfo("divisor", number);
    report.addMessage(msg.build());
}

From source file:com.github.fge.jsonschema.keyword.validator.helpers.DivisorValidator.java

@Override
protected final void validateDecimal(final ProcessingReport report, final MessageBundle bundle,
        final FullData data) throws ProcessingException {
    final JsonNode node = data.getInstance().getNode();
    final BigDecimal instanceValue = node.decimalValue();
    final BigDecimal decimalValue = number.decimalValue();

    final BigDecimal remainder = instanceValue.remainder(decimalValue);

    /*//from ww w .  j ava2s  . c o  m
     * We cannot use equality! As far as BigDecimal goes,
     * "0" and "0.0" are NOT equal. But .compareTo() returns the correct
     * result.
     */
    if (remainder.compareTo(BigDecimal.ZERO) == 0)
        return;

    report.error(newMsg(data, bundle, "err.common.divisor.nonZeroRemainder").putArgument("value", node)
            .putArgument("divisor", number));
}

From source file:edu.ku.brc.specify.config.LatLonConverter.java

/**
 * Converts BigDecimal to Degrees and Decimal Minutes.
 * @param bd the DigDecimal to be converted.
 * @return a 2 piece string//from www. ja v a2 s .c o m
 */
public static String convertToDDMMMM(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {
    if (bd.doubleValue() == 0.0) {
        return "0.0";
    }

    if (useDB) {
        BigDecimal remainder = bd.remainder(one);

        BigDecimal num = bd.subtract(remainder);

        BigDecimal minutes = remainder.multiply(sixty).abs();

        //System.out.println("["+decFormatter2.format(num)+"]["+minutes+"]");
        return decFormatter2.format(num) + " " + decFormatter2.format(minutes);

    }
    //else

    boolean addMinSecsSyms = degreesFMT != DEGREES_FORMAT.None;

    double num = Math.abs(bd.doubleValue());
    int whole = (int) Math.floor(num);
    double remainder = num - whole;

    double minutes = remainder * 60.0;
    //System.out.println("["+whole+"]["+String.format("%10.10f", new Object[] {minutes})+"]");

    StringBuilder sb = new StringBuilder();
    sb.append(whole);
    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append("\u00B0");
    }
    sb.append(' ');

    // round to four decimal places of precision
    //minutes = Math.round(minutes*10000) / 10000;

    sb.append(String.format("%" + 2 + "." + decimalLen + "f", minutes));
    if (addMinSecsSyms)
        sb.append("'");

    if (degreesFMT == DEGREES_FORMAT.String || alwaysIncludeDir) {
        int inx = bd.doubleValue() < 0.0 ? 1 : 0;
        if (direction != DIRECTION.None) {
            sb.append(' ');
            sb.append(direction == DIRECTION.NorthSouth ? northSouth[inx] : eastWest[inx]);
        }
    }
    //return whole + (degreesFMT == DEGREES_FORMAT.Symbol ? "\u00B0" : "") + " " + StringUtils.strip(String.format("%10.10f", new Object[] {minutes}), "0");
    return sb.toString();

}

From source file:edu.ku.brc.specify.config.LatLonConverter.java

/**
 * Converts BigDecimal to Degrees, Minutes and Decimal Seconds.
 * @param bd the DigDecimal to be converted.
 * @return a 3 piece string/*from w  w  w.j a v  a2 s.  com*/
 */
public static String convertToDDMMSS(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {

    if (bd.doubleValue() == 0.0) {
        return "0." + zeroes.substring(0, decimalLen);
    }

    if (useDB) {
        BigDecimal remainder = bd.remainder(one);

        BigDecimal num = bd.subtract(remainder);

        BigDecimal minutes = new BigDecimal(remainder.multiply(sixty).abs().intValue());
        BigDecimal secondsFraction = remainder.abs().multiply(sixty).subtract(minutes);
        BigDecimal seconds = secondsFraction.multiply(sixty);

        //System.out.println("["+decFormatter2.format(num)+"]["+minutes+"]["+seconds+"]");

        return decFormatter2.format(num) + " " + decFormatter2.format(minutes) + " "
                + decFormatter.format(seconds);

    }
    //else

    double num = Math.abs(bd.doubleValue());
    int whole = (int) Math.floor(num);
    double remainder = num - whole;

    double minutes = remainder * 60.0;
    int minutesWhole = (int) Math.floor(minutes);
    double secondsFraction = minutes - minutesWhole;
    double seconds = secondsFraction * 60.0;

    boolean addMinSecsSyms = degreesFMT != DEGREES_FORMAT.None;

    if (minutesWhole == 60) {
        whole += 1;
        minutesWhole = 0;
    }

    // round to 2 decimal places precision
    seconds = Math.round(seconds * 1000) / 1000.0;

    int secondsWhole = (int) Math.floor(seconds);
    if (secondsWhole == 60) {
        minutesWhole += 1;
        seconds = 0.0;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(whole);
    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append(DEGREES_SYMBOL);
    }
    sb.append(' ');
    sb.append(minutesWhole);
    if (addMinSecsSyms)
        sb.append("'");
    sb.append(' ');

    sb.append(String.format("%2." + decimalLen + "f", seconds));
    if (addMinSecsSyms)
        sb.append("\"");

    if (degreesFMT == DEGREES_FORMAT.String || alwaysIncludeDir) {
        int inx = bd.doubleValue() < 0.0 ? 1 : 0;
        if (direction != DIRECTION.None) {
            sb.append(' ');
            sb.append(direction == DIRECTION.NorthSouth ? northSouth[inx] : eastWest[inx]);
        }
    }
    //System.err.println("["+sb.toString()+"]");
    //return whole + (DEGREES_FORMAT.None ? "\u00B0" : "") + " " + minutesWhole + " " + StringUtils.strip(String.format("%12.10f", new Object[] {seconds}), "0");
    return sb.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  a v  a 2  s . co  m*/
 *            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:org.apache.hadoop.hive.common.type.HiveIntervalDayTime.java

public void set(BigDecimal totalSecondsBd) {
    long totalSeconds = totalSecondsBd.longValue();
    BigDecimal fractionalSecs = totalSecondsBd.remainder(BigDecimal.ONE);
    int nanos = fractionalSecs.multiply(IntervalDayTimeUtils.NANOS_PER_SEC_BD).intValue();
    set(totalSeconds, nanos);//from w  w w. ja v  a 2s. c  o  m
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsRateInquire(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");

    // check for 0 weight
    BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight");
    if (shippableWeight.compareTo(BigDecimal.ZERO) == 0) {
        // TODO: should we return an error, or $0.00 ?
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale));
    }/*from  w ww . j a v a  2  s.c  o m*/

    // get the origination ZIP
    String originationZip = null;
    GenericValue productStore = ProductStoreWorker.getProductStore(((String) context.get("productStoreId")),
            delegator);
    if (productStore != null && productStore.get("inventoryFacilityId") != null) {
        GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator,
                productStore.getString("inventoryFacilityId"),
                UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
        if (facilityContactMech != null) {
            try {
                GenericValue shipFromAddress = EntityQuery.use(delegator).from("PostalAddress")
                        .where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne();
                if (shipFromAddress != null) {
                    originationZip = shipFromAddress.getString("postalCode");
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
        }
    }
    if (UtilValidate.isEmpty(originationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineOriginationZip", locale));
    }

    // get the destination ZIP
    String destinationZip = null;
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    if (UtilValidate.isNotEmpty(shippingContactMechId)) {
        try {
            GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress")
                    .where("contactMechId", shippingContactMechId).queryOne();
            if (shipToAddress != null) {
                if (!domesticCountries.contains(shipToAddress.getString("countryGeoId"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsRateInquiryOnlyInUsDestinations", locale));
                }
                destinationZip = shipToAddress.getString("postalCode");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (UtilValidate.isEmpty(destinationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineDestinationZip", locale));
    }

    // get the service code
    String serviceCode = null;
    try {
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId",
                        (String) context.get("carrierPartyId"), "roleTypeId",
                        (String) context.get("carrierRoleTypeId"))
                .queryOne();
        if (carrierShipmentMethod != null) {
            serviceCode = carrierShipmentMethod.getString("carrierServiceCode").toUpperCase();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (UtilValidate.isEmpty(serviceCode)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineServiceCode", locale));
    }

    // create the request document
    Document requestDocument = createUspsRequestDocument("RateV2Request", true, delegator,
            shipmentGatewayConfigId, resource);

    // TODO: 70 lb max is valid for Express, Priority and Parcel only - handle other methods
    BigDecimal maxWeight = new BigDecimal("70");
    String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight",
            resource, "shipment.usps.max.estimate.weight", "70");
    try {
        maxWeight = new BigDecimal(maxWeightStr);
    } catch (NumberFormatException e) {
        Debug.logWarning(
                "Error parsing max estimate weight string [" + maxWeightStr + "], using default instead",
                module);
        maxWeight = new BigDecimal("70");
    }

    List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo"));
    List<Map<String, BigDecimal>> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight);
    boolean isOnePackage = packages.size() == 1; // use shippableWeight if there's only one package
    // TODO: Up to 25 packages can be included per request - handle more than 25
    for (ListIterator<Map<String, BigDecimal>> li = packages.listIterator(); li.hasNext();) {
        Map<String, BigDecimal> packageMap = li.next();

        BigDecimal packageWeight = isOnePackage ? shippableWeight
                : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO);
        if (packageWeight.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }

        Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                requestDocument);
        packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples)

        UtilXml.addChildElementValue(packageElement, "Service", serviceCode, requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipOrigination",
                StringUtils.substring(originationZip, 0, 5), requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipDestination",
                StringUtils.substring(destinationZip, 0, 5), requestDocument);

        BigDecimal weightPounds = packageWeight.setScale(0, BigDecimal.ROUND_FLOOR);
        // for Parcel post, the weight must be at least 1 lb
        if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPounds.compareTo(BigDecimal.ONE) < 0)) {
            weightPounds = BigDecimal.ONE;
            packageWeight = BigDecimal.ZERO;
        }
        // (packageWeight % 1) * 16 (Rounded up to 0 dp)
        BigDecimal weightOunces = packageWeight.remainder(BigDecimal.ONE).multiply(new BigDecimal("16"))
                .setScale(0, BigDecimal.ROUND_CEILING);

        UtilXml.addChildElementValue(packageElement, "Pounds", weightPounds.toPlainString(), requestDocument);
        UtilXml.addChildElementValue(packageElement, "Ounces", weightOunces.toPlainString(), requestDocument);

        // TODO: handle other container types, package sizes, and machinable packages
        // IMPORTANT: Express or Priority Mail will fail if you supply a Container tag: you will get a message like
        // Invalid container type. Valid container types for Priority Mail are Flat Rate Envelope and Flat Rate Box.
        /* This is an official response from the United States Postal Service:
        The <Container> tag is used to specify the flat rate mailing options, or the type of large or oversized package being mailed.
        If you are wanting to get regular Express Mail rates, leave the <Container> tag empty, or do not include it in the request at all.
         */
        if ("Parcel".equalsIgnoreCase(serviceCode)) {
            UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
        }
        UtilXml.addChildElementValue(packageElement, "Size", "REGULAR", requestDocument);
        UtilXml.addChildElementValue(packageElement, "Machinable", "false", requestDocument);
    }

    // send the request
    Document responseDocument = null;
    try {
        responseDocument = sendUspsRequest("RateV2", requestDocument, delegator, shipmentGatewayConfigId,
                resource, locale);
    } catch (UspsRequestException e) {
        Debug.logInfo(e, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    if (responseDocument == null) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    List<? extends Element> rates = UtilXml.childElementList(responseDocument.getDocumentElement(), "Package");
    if (UtilValidate.isEmpty(rates)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    BigDecimal estimateAmount = BigDecimal.ZERO;
    for (Element packageElement : rates) {
        try {
            Element postageElement = UtilXml.firstChildElement(packageElement, "Postage");
            BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(postageElement, "Rate"));
            estimateAmount = estimateAmount.add(packageAmount);
        } catch (NumberFormatException e) {
            Debug.logInfo(e, module);
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shippingEstimateAmount", estimateAmount);
    return result;
}