Example usage for java.math BigDecimal toPlainString

List of usage examples for java.math BigDecimal toPlainString

Introduction

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

Prototype

public String toPlainString() 

Source Link

Document

Returns a string representation of this BigDecimal without an exponent field.

Usage

From source file:au.org.ala.delta.translation.key.KeyStateTranslator.java

/**
 * Produces a state description of a key state defined for a numeric character.
 * @param keyChar the character as defined by the KEY STATES directive.
 * @param state details of the redefined state to describe.
 * @param separator the separator to use.
 * @return a description of the supplied state of the supplied character.
 *///w  ww .  j a v  a2s  .com
private String translateNumericState(IdentificationKeyCharacter keyChar, NumericKeyState state) {

    BigDecimal min = state.min();
    BigDecimal max = state.max();
    List<String> states = new ArrayList<String>();

    String separator = " " + Words.word(Word.TO) + " ";
    Values values = new Values(states, separator);

    if (keyChar.getCharacter().getCharacterType().isNumeric()) {

        if (min.equals(MIN_VALUE)) {
            values.setPrefix(Words.word(Word.UP_TO));
            states.add(max.toPlainString());
        } else if (max.equals(MAX_VALUE)) {
            values.setSuffix(Words.word(Word.OR_MORE));
            states.add(min.toPlainString());
        } else {
            states.add(min.toPlainString());
            if (min.compareTo(max) != 0) {
                states.add(max.toPlainString());
            }
        }
    }

    AttributeTranslator at = _attributeTranslatorFactory.translatorFor(keyChar.getCharacter());

    StringBuffer result = new StringBuffer();
    if (StringUtils.isNotBlank((values.getPrefix()))) {
        result.append(values.getPrefix()).append(" ");
    }

    result.append(at.translateValues(values));

    if (StringUtils.isNotBlank(values.getSuffix())) {
        result.append(" ").append(values.getSuffix());
    }
    return result.toString();
}

From source file:org.libreplan.web.orders.AssignedHoursToOrderElementModel.java

@Override
public String getTotalExpenses() {
    if ((orderElement != null) && (orderElement.getSumExpenses() != null)) {
        BigDecimal directExpenses = orderElement.getSumExpenses().getTotalDirectExpenses();
        BigDecimal indirectExpenses = orderElement.getSumExpenses().getTotalIndirectExpenses();
        BigDecimal total = BigDecimal.ZERO;
        if (directExpenses != null) {
            total = total.add(directExpenses);
        }//from ww w . j av a 2 s. c  om
        if (indirectExpenses != null) {
            total = total.add(indirectExpenses);
        }
        return total.toPlainString();
    }
    return BigDecimal.ZERO.toPlainString();
}

From source file:org.openbravo.advpaymentmngt.filterexpression.AddPaymentDefaultValuesHandler.java

/**
 * Customer credit default value//  www .j  a v a  2  s.  c o  m
 * 
 * @param requestMap
 *          map with parameters
 */
public String getDefaultCustomerCredit(Map<String, String> requestMap) throws JSONException {
    String strBusinessPartnerId = getDefaultReceivedFrom(requestMap);
    String strOrgId = getOrganization(requestMap);
    String strReceipt = getDefaultIsSOTrx(requestMap);
    if (StringUtils.isEmpty(strBusinessPartnerId) || strReceipt == null) {
        return null;
    }
    BusinessPartner bpartner = OBDal.getInstance().get(BusinessPartner.class, strBusinessPartnerId);
    Organization org = OBDal.getInstance().get(Organization.class, strOrgId);
    BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, "Y".equals(strReceipt),
            org);
    return customerCredit.toPlainString();

}

From source file:org.apache.hive.storage.jdbc.spitter.DecimalIntervalSplitter.java

@Override
public List<MutablePair<String, String>> getIntervals(String lowerBound, String upperBound, int numPartitions,
        TypeInfo typeInfo) {//w  w w  . ja v  a 2  s.  c o  m
    List<MutablePair<String, String>> intervals = new ArrayList<>();
    DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo;
    int scale = decimalTypeInfo.getScale();
    BigDecimal decimalLower = new BigDecimal(lowerBound);
    BigDecimal decimalUpper = new BigDecimal(upperBound);
    BigDecimal decimalInterval = (decimalUpper.subtract(decimalLower)).divide(new BigDecimal(numPartitions),
            MathContext.DECIMAL64);
    BigDecimal splitDecimalLower, splitDecimalUpper;
    for (int i = 0; i < numPartitions; i++) {
        splitDecimalLower = decimalLower.add(decimalInterval.multiply(new BigDecimal(i))).setScale(scale,
                RoundingMode.HALF_EVEN);
        splitDecimalUpper = decimalLower.add(decimalInterval.multiply(new BigDecimal(i + 1))).setScale(scale,
                RoundingMode.HALF_EVEN);
        if (splitDecimalLower.compareTo(splitDecimalUpper) < 0) {
            intervals.add(new MutablePair<String, String>(splitDecimalLower.toPlainString(),
                    splitDecimalUpper.toPlainString()));
        }
    }
    return intervals;
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatImportHelper.java

private Object convertNumberTypes(Object val, HCatFieldSchema hfs) {
    HCatFieldSchema.Type hfsType = hfs.getType();

    if (!(val instanceof Number)) {
        return null;
    }//  w  w  w.  j  av a2 s.  co  m
    if (val instanceof BigDecimal && hfsType == HCatFieldSchema.Type.STRING
            || hfsType == HCatFieldSchema.Type.VARCHAR || hfsType == HCatFieldSchema.Type.CHAR) {
        BigDecimal bd = (BigDecimal) val;
        String bdStr = null;
        if (bigDecimalFormatString) {
            bdStr = bd.toPlainString();
        } else {
            bdStr = bd.toString();
        }
        if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
            HiveVarchar hvc = new HiveVarchar(bdStr, vti.getLength());
            return hvc;
        } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
            CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
            HiveChar hChar = new HiveChar(bdStr, cti.getLength());
            return hChar;
        } else {
            return bdStr;
        }
    }
    Number n = (Number) val;
    if (hfsType == HCatFieldSchema.Type.TINYINT) {
        return n.byteValue();
    } else if (hfsType == HCatFieldSchema.Type.SMALLINT) {
        return n.shortValue();
    } else if (hfsType == HCatFieldSchema.Type.INT) {
        return n.intValue();
    } else if (hfsType == HCatFieldSchema.Type.BIGINT) {
        return n.longValue();
    } else if (hfsType == HCatFieldSchema.Type.FLOAT) {
        return n.floatValue();
    } else if (hfsType == HCatFieldSchema.Type.DOUBLE) {
        return n.doubleValue();
    } else if (hfsType == HCatFieldSchema.Type.BOOLEAN) {
        return n.byteValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
    } else if (hfsType == HCatFieldSchema.Type.STRING) {
        return n.toString();
    } else if (hfsType == HCatFieldSchema.Type.VARCHAR) {
        VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo();
        HiveVarchar hvc = new HiveVarchar(val.toString(), vti.getLength());
        return hvc;
    } else if (hfsType == HCatFieldSchema.Type.CHAR) {
        CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo();
        HiveChar hChar = new HiveChar(val.toString(), cti.getLength());
        return hChar;
    } else if (hfsType == HCatFieldSchema.Type.DECIMAL) {
        BigDecimal bd = new BigDecimal(n.doubleValue(), MathContext.DECIMAL128);
        return HiveDecimal.create(bd);
    }
    return null;
}

From source file:com.stratio.cassandra.index.schema.ColumnMapperBigDecimal.java

/** {@inheritDoc} */
@Override//w ww  . j  av  a  2  s .co  m
public String indexValue(String name, Object value) {

    // Check not null
    if (value == null) {
        return null;
    }

    // Parse big decimal
    String svalue = value.toString();
    BigDecimal bd;
    try {
        bd = new BigDecimal(value.toString());
    } catch (NumberFormatException e) {
        String message = String.format("Field %s requires a base 10 decimal, but found \"%s\"", name, svalue);
        throw new IllegalArgumentException(message);
    }

    // Split integer and decimal part
    bd = bd.stripTrailingZeros();
    String[] parts = bd.toPlainString().split("\\.");
    String integerPart = parts[0];
    String decimalPart = parts.length == 1 ? "0" : parts[1];

    if (integerPart.replaceFirst("-", "").length() > integerDigits) {
        throw new IllegalArgumentException("Too much digits in integer part");
    }
    if (decimalPart.length() > decimalDigits) {
        throw new IllegalArgumentException("Too much digits in decimal part");
    }

    BigDecimal complemented = bd.add(complement);
    String bds[] = complemented.toString().split("\\.");
    integerPart = bds[0];
    decimalPart = bds.length == 2 ? bds[1] : "0";
    integerPart = StringUtils.leftPad(integerPart, integerDigits + 1, '0');

    return integerPart + "." + decimalPart;
}

From source file:org.dash.wallet.integration.uphold.ui.UpholdWithdrawalDialog.java

@SuppressLint("SetTextI18n")
private void showCommitTransactionConfirmationDialog(boolean deductFeeFromAmount) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
    dialogBuilder.setTitle(R.string.uphold_withdrawal_confirm_title);

    View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.uphold_confirm_transaction_dialog,
            null);/*from   w ww  .  java 2  s .  c o m*/
    TextView amountTxt = contentView.findViewById(R.id.uphold_withdrawal_amount);
    TextView feeTxt = contentView.findViewById(R.id.uphold_withdrawal_fee);
    TextView totalTxt = contentView.findViewById(R.id.uphold_withdrawal_total);
    View deductFeeDisclaimer = contentView
            .findViewById(R.id.uphold_withdrawal_confirmation_fee_deduction_disclaimer);

    BigDecimal fee = transaction.getOrigin().getFee();
    final BigDecimal baseAmount = transaction.getOrigin().getBase();
    final BigDecimal total = transaction.getOrigin().getAmount();

    if (total.compareTo(balance) > 0) {
        transfer(balance.subtract(fee), true);
        return;
    }

    amountTxt.setText(baseAmount.toPlainString());
    feeTxt.setText(fee.toPlainString());
    totalTxt.setText(total.toPlainString());

    if (deductFeeFromAmount) {
        deductFeeDisclaimer.setVisibility(View.VISIBLE);
    }

    dialogBuilder.setView(contentView);
    dialogBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            commitTransaction();
        }
    });

    dialogBuilder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            transaction = null;
        }
    });
    dialogBuilder.setCancelable(false);
    dialogBuilder.show();
}

From source file:com.music.service.PurchaseService.java

public String getButtonCode(BigDecimal price, long purchaseId) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    ButtonRequest buttonRequest = new ButtonRequest();
    buttonRequest.setCurrency("btc");
    buttonRequest.setCustom(String.valueOf(purchaseId));
    buttonRequest.setPrice(price.toPlainString());
    buttonRequest.setType("buy_now");
    buttonRequest.setName("Computer-generated tracks");
    ResponseEntity<String> entity = template.postForEntity(
            "https://coinbase.com/api/v1/buttons?api_key=" + coinbaseKey, buttonRequest, String.class);
    String json = entity.getBody();

    try {/*from ww w .  j  ava  2s .c  o m*/
        JsonNode node = jsonMapper.readTree(json);

        return node.get("button").get("code").asText();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatExportHelper.java

private Object convertDecimalTypes(Object val, String javaColType) {
    HiveDecimal hd = (HiveDecimal) val;
    BigDecimal bd = hd.bigDecimalValue();

    if (javaColType.equals(BIG_DECIMAL_TYPE)) {
        return bd;
    } else if (javaColType.equals(STRING_TYPE)) {
        String bdStr = null;//  www .  j ava2 s.  c o m
        if (bigDecimalFormatString) {
            bdStr = bd.toPlainString();
        } else {
            bdStr = bd.toString();
        }
        return bdStr;
    }
    return null;
}

From source file:org.ofbiz.accounting.thirdparty.paypal.PayPalServices.java

public static Map<String, Object> doExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {//from  w ww. j  av  a 2s. co  m
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod");
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod");
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal = processAmount.subtract(shippingTotal).subtract(taxTotal).setScale(2,
            BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.setScale(2).toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalPaymentSetting, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        return ServiceUtil.returnError("An error occurred while communicating with PayPal");
    }

    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
        if (errorMessages.containsKey("10417")) {
            // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
            // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
            boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
            if (retry) {
                context.put("_RETRY_", false);
                return PayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

    Map<String, Object> outMap = null;
    try {
        outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
        Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
        return outMap;
    }
    return ServiceUtil.returnSuccess();
}