Example usage for java.math BigDecimal toString

List of usage examples for java.math BigDecimal toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns the string representation of this BigDecimal , using scientific notation if an exponent is needed.

Usage

From source file:com.stratio.cassandra.lucene.schema.mapping.BigDecimalMapper.java

/** {@inheritDoc} */
@Override/*from  w  ww . ja v a  2s .c  o  m*/
protected String doBase(String name, Object value) {

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

    // Split integer and decimal part
    bd = bd.stripTrailingZeros();
    String[] parts = bd.toPlainString().split("\\.");
    validateIntegerPart(name, value, parts);
    validateDecimalPart(name, value, parts);

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

    return integerPart + "." + decimalPart;
}

From source file:cherry.foundation.crypto.SecureBigDecimalEncoderTest.java

@Test
public void testEncodeDecode() throws Exception {
    SecureBigDecimalEncoder encoder = createSecureBigDecimalEncoder();
    for (int i = 0; i < 100; i++) {
        BigDecimal plain = BigDecimal.valueOf(random.nextDouble());
        String crypto = encoder.encode(plain);
        assertThat(crypto, is(not(plain.toString())));
        assertThat(encoder.decode(crypto), is(plain));
    }//w ww  .  j  av a 2s . c o  m
}

From source file:ch.algotrader.option.OptionSymbol.java

/**
 * Generates the symbole for the specified {@link ch.algotrader.entity.security.OptionFamily}.
 *
 * Example//from w  w w . j  a v  a  2s  .  c o m
 *     <table>
 *     <tr><td><b>Pattern</b></td><td><b>Description</b></td><td><b>Example</b></td></tr>
 *     <tr><td>N</td><td>Name</td><td>CrudeOil</td></tr>
 *     <tr><td>CR</td><td>SymbolRoot</td><td>CL</td></tr>
 *     <tr><td>C</td><td>Currency</td><td>USD</td></tr>
 *     <tr><td>CS</td><td>ContractSize</td><td>1000</td></tr>
 *     <tr><td>M</td><td>Month 1-digit</td><td>6</td></tr>
 *     <tr><td>MM</td><td>Month 2-digit</td><td>06</td></tr>
 *     <tr><td>MMM</td><td>Month Short</td><td>JUN</td></tr>
 *     <tr><td>MMMM</td><td>Month Long</td><td>June</td></tr>
 *     <tr><td>YY</td><td>Year 2-digit</td><td>16</td></tr>
 *     <tr><td>YYYY</td><td>Year 4-digit</td><td>2016</td></tr>
 *     <tr><td>W</td><td>Week of Month</td><td>3</td></tr>
 *     <tr><td>T</td><td>Type Short</td><td>C</td></tr>
 *     <tr><td>TT</td><td>Type Long</td><td>CALL</td></tr>
 *     <tr><td>S</td><td>Strike</td><td>500</td></tr>
 *     </table>
 */
public static String getSymbol(OptionFamily family, LocalDate expiration, OptionType type, BigDecimal strike,
        String pattern) {

    String[] placeHolders = new String[] { "N", "SR", "CS", "C", "MMMM", "MMM", "MM", "MR", "YYYY", "YY", "YR",
            "W", "TT", "T", "S" };

    String[] values = new String[] { family.getName(), family.getSymbolRoot(),
            RoundUtil.getBigDecimal(family.getContractSize(), 0).toString(), family.getCurrency().toString(),
            DateTimePatterns.MONTH_LONG.format(expiration).toUpperCase(),
            DateTimePatterns.MONTH_SHORT.format(expiration).toUpperCase(),
            DateTimePatterns.MONTH_2_DIGIT.format(expiration).toUpperCase(),
            OptionType.CALL.equals(type) ? monthCallEnc[expiration.getMonth().getValue() - 1]
                    : monthPutEnc[expiration.getMonthValue() - 1],
            DateTimePatterns.YEAR_4_DIGIT.format(expiration), DateTimePatterns.YEAR_2_DIGIT.format(expiration),
            yearEnc[expiration.getYear() % 10], DateTimePatterns.WEEK_OF_MONTH.format(expiration),
            type.toString(), type.toString().substring(0, 1), strike.toString() };

    return StringUtils.replaceEach(pattern, placeHolders, values);
}

From source file:org.hoteia.qalingo.core.solr.service.impl.ProductSkuSolrServiceImpl.java

public void addOrUpdateProductSku(final ProductSku productSku, final MarketArea marketArea,
        final Retailer retailer) throws SolrServerException, IOException {
    if (productSku.getId() == null) {
        throw new IllegalArgumentException("Id  cannot be blank or null.");
    }//from  ww w . j a v  a  2 s. co  m
    if (logger.isDebugEnabled()) {
        logger.debug("Indexing productSku " + productSku.getId());
        logger.debug("Indexing productSku " + productSku.getBusinessName());
        logger.debug("Indexing productSku " + productSku.getDescription());
        logger.debug("Indexing productSku " + productSku.getCode());
    }
    ProductSkuSolr productSkuSolr = new ProductSkuSolr();
    productSkuSolr.setId(productSku.getId());
    productSkuSolr.setBusinessname(productSku.getBusinessName());
    productSkuSolr.setDescription(productSku.getDescription());
    productSkuSolr.setCode(productSku.getCode());
    ProductSkuPrice productSkuPrice = productSku.getPrice(marketArea.getId(), retailer.getId());
    if (productSkuPrice != null) {
        BigDecimal salePrice = productSkuPrice.getSalePrice();
        productSkuSolr.setPrice(salePrice.toString());
    }
    productSkuSolrServer.addBean(productSkuSolr);
    productSkuSolrServer.commit();
}

From source file:com.coinblesk.server.controller.ForexController.java

/**
 * Returns up to date exchangerate BTC/CHF
 *
 * @return CustomResponseObject with exchangeRate BTC/CHF as a String
 *//*w  w  w  .  jav  a 2s.  c  om*/
@RequestMapping(value = "/rate/{from}-{to}", method = GET, produces = APPLICATION_JSON_UTF8_VALUE)
@ApiVersion({ "v2" })
@ResponseBody
public ResponseEntity<ExchangeRateTO> forexExchangeRate(@PathVariable(value = "from") String from,
        @PathVariable(value = "to") String to) {

    LOG.debug("{exchange-rate} - Received exchange rate request for currency {}/{}", from, to);
    ExchangeRateTO output = new ExchangeRateTO();
    try {
        if (!Pattern.matches("[A-Z]{3}", from) || !Pattern.matches("[A-Z]{3}", to)) {
            output.type(SERVER_ERROR).message("unknown currency symbol");
            return new ResponseEntity<>(output, BAD_REQUEST);
        }
        BigDecimal exchangeRate = forexExchangeRateService.getExchangeRate(from, to);
        output.name(from + to);
        output.rate(exchangeRate.toString());
        output.setSuccess();

        LOG.debug("{exchange-rate} - {}, rate: {}", output.name(), output.rate());
        return new ResponseEntity<>(output, OK);

    } catch (Exception e) {
        LOG.error("{exchange-rate} - SERVER_ERROR - exception: ", e);
        output.type(SERVER_ERROR);
        output.message(e.getMessage());
        return new ResponseEntity<>(output, BAD_REQUEST);
    }
}

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/*from  w w w  . j  ava2  s.com*/
 * @return
 */
private String bigDecimalToSignedString(BigDecimal value) {
    if (value.signum() < 0) {
        return value.toString();
    } else {
        return "+" + value.toString();
    }
}

From source file:com.panet.imeta.core.xml.XMLHandler.java

/**
 * Build an XML string (including a carriage return) for a certain tag
 * BigDecimal value//from   ww  w  . ja  v  a  2 s. c o m
 * 
 * @param tag
 *            The XML tag
 * @param val
 *            The BigDecimal value of the tag
 * 
 * @return The XML String for the tag.
 */
public static final String addTagValue(String tag, BigDecimal val, boolean cr) {
    return addTagValue(tag, val != null ? val.toString() : (String) null, true);
}

From source file:Money.java

public Money(BigDecimal value) {
    this(value.toString());
}

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

/** {@inheritDoc} */
@Override/*from  www .  j  a  v a  2  s.c o 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:net.sourceforge.msscodefactory.v1_10.MSSBamMssCF.MSSBamMssCFBindNumberDefMaxValue.java

public String expandBody(MssCFGenContext genContext) {
    final String S_ProcName = "MSSBamMssCFBindNumberDefMaxValue.expandBody() ";

    if (genContext == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), "expandBody", 1,
                "genContext");
    }//from  www.  java 2 s  .  co  m

    IMssCFAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), "expandBody", 1,
                "genContext.getGenDef()");
    }

    String ret;

    if (genDef instanceof IMSSBamBLNumberDefObj) {
        BigDecimal maxValue = ((IMSSBamBLNumberDefObj) genDef).getOptionalMaxValue();
        if (maxValue == null) {
            ret = null;
        } else {
            ret = maxValue.toString();
        }
    } else {
        throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException(getClass(), "expandBody",
                "genContext.getGenDef()", genDef, "IMSSBamBLNumberDefObj");
    }

    return (ret);
}