Example usage for java.math BigDecimal valueOf

List of usage examples for java.math BigDecimal valueOf

Introduction

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

Prototype

public static BigDecimal valueOf(double val) 

Source Link

Document

Translates a double into a BigDecimal , using the double 's canonical string representation provided by the Double#toString(double) method.

Usage

From source file:com.qcadoo.model.types.FieldTypeFactoryTest.java

@Test
public void shouldReturnDecimalType() throws Exception {
    // when//from   w ww  .ja va2s.  c  o  m
    FieldType fieldType = new DecimalType();

    // then
    assertThat(fieldType, is(DecimalType.class));
    assertEquals(BigDecimal.class, fieldType.getType());
    assertTrue(fieldType.toObject(fieldDefinition, BigDecimal.valueOf(1.21)).isValid());
    assertTrue(fieldType.toObject(fieldDefinition, BigDecimal.valueOf(1)).isValid());
    assertTrue(fieldType.toObject(fieldDefinition, BigDecimal.valueOf(1)).isValid());
    assertTrue(fieldType.toObject(fieldDefinition, BigDecimal.valueOf(1234567)).isValid());
}

From source file:de.hybris.platform.commercefacades.search.converters.populator.SearchResultProductPopulator.java

protected void populatePrices(final SearchResultValueData source, final ProductData target) {
    // Pull the volume prices flag
    final Boolean volumePrices = this.<Boolean>getValue(source, "volumePrices");
    target.setVolumePricesFlag(volumePrices == null ? Boolean.FALSE : volumePrices);

    // Pull the price value for the current currency
    final Double priceValue = this.<Double>getValue(source, "priceValue");
    if (priceValue != null) {
        final PriceData priceData = getPriceDataFactory().create(PriceDataType.BUY,
                BigDecimal.valueOf(priceValue.doubleValue()), getCommonI18NService().getCurrentCurrency());
        target.setPrice(priceData);//from   www.j a  v a 2 s. com
    }
}

From source file:com.realdolmen.rdfleet.soap.MileageUpdateLogicTest.java

private Car createCar() {
    Car car = new Car();
    car.setFunctionalLevel(2);//  ww  w .  j a va  2  s. com
    car.setMake("Audi");
    car.setModel("A1");
    car.setAmountDowngrade(BigDecimal.valueOf(2315.25));
    car.setFuelType(FuelType.DIESEL);
    car.setAmountUpgrade(BigDecimal.valueOf(0).setScale(2, RoundingMode.HALF_UP));
    car.setListPrice(BigDecimal.valueOf(25343.22));
    car.setTyreType(TyreType.ALUMINIUM);
    car.setTimeOfDeliveryInDays(Duration.ofDays(150));
    return car;
}

From source file:se.backede.jeconomix.forms.report.SingleTransactionReport.java

private DefaultCategoryDataset createDataset(TransactionReportDto reports) {

    String lineTitle = "Kronor";

    Map<Month, BigDecimal> sums = new HashMap<>();

    List<Month> monthList = new LinkedList<>(Arrays.asList(Month.values()));

    monthList.forEach((month) -> {/* w  ww . ja  va 2s .c o  m*/
        sums.put(month, BigDecimal.valueOf(0));
    });

    reports.getTransctions().forEach((TransactionDto transaction) -> {
        monthList.stream().filter((month) -> (transaction.getBudgetMonth().equals(month)))
                .forEachOrdered((month) -> {
                    BigDecimal currentSum = sums.get(month);
                    if (transaction.getSum() != null) {
                        double abs = Math.abs(transaction.getSum().doubleValue());
                        BigDecimal newSum = currentSum.add(BigDecimal.valueOf(abs));
                        sums.put(month, newSum);
                    }
                });
    });

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.addValue(sums.get(Month.JANUARY), lineTitle, "Jan");
    dataset.addValue(sums.get(Month.FEBRUARY), lineTitle, "Feb");
    dataset.addValue(sums.get(Month.MARCH), lineTitle, "Mar");
    dataset.addValue(sums.get(Month.APRIL), lineTitle, "Apr");
    dataset.addValue(sums.get(Month.MAY), lineTitle, "May");
    dataset.addValue(sums.get(Month.JUNE), lineTitle, "Jun");
    dataset.addValue(sums.get(Month.JULY), lineTitle, "Jul");
    dataset.addValue(sums.get(Month.AUGUST), lineTitle, "Aug");
    dataset.addValue(sums.get(Month.SEPTEMBER), lineTitle, "Sep");
    dataset.addValue(sums.get(Month.OCTOBER), lineTitle, "Oct");
    dataset.addValue(sums.get(Month.NOVEMBER), lineTitle, "Nov");
    dataset.addValue(sums.get(Month.DECEMBER), lineTitle, "Dec");
    return dataset;
}

From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java

public KmerRangePartition[] getEqualAreaPartitions() {
    KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions];

    // calc 4^kmerSize
    BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize);
    BigDecimal bdkmerend = new BigDecimal(kmerend);
    // moves between x (0~1) y (0~1)
    // sum of area (0.5)
    double kmerArea = 0.5;
    double sliceArea = kmerArea / this.numPartitions;

    // we think triangle is horizontally flipped so calc get easier.
    double x1 = 0;

    List<BigInteger> widths = new ArrayList<BigInteger>();
    BigInteger widthSum = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        // x2*x2 = 2*sliceArea + x1*x1
        double temp = (2 * sliceArea) + (x1 * x1);
        double x2 = Math.sqrt(temp);

        BigDecimal bdx1 = BigDecimal.valueOf(x1);
        BigDecimal bdx2 = BigDecimal.valueOf(x2);

        // if i increases, bdw will be decreased
        BigDecimal bdw = bdx2.subtract(bdx1);

        BigInteger bw = bdw.multiply(bdkmerend).toBigInteger();
        if (bw.compareTo(BigInteger.ZERO) <= 0) {
            bw = BigInteger.ONE;//  w w w .  j  ava2  s.  c o  m
        }

        if (widthSum.add(bw).compareTo(kmerend) > 0) {
            bw = kmerend.subtract(widthSum);
        }

        if (i == this.numPartitions - 1) {
            // last case
            if (widthSum.add(bw).compareTo(kmerend) < 0) {
                bw = kmerend.subtract(widthSum);
            }
        }

        // save it
        widths.add(bw);
        widthSum = widthSum.add(bw);

        x1 = x2;
    }

    BigInteger cur_begin = BigInteger.ZERO;
    for (int i = 0; i < this.numPartitions; i++) {
        BigInteger slice_width = widths.get(this.numPartitions - 1 - i);

        BigInteger slice_begin = cur_begin;

        if (slice_begin.add(slice_width).compareTo(kmerend) > 0) {
            slice_width = kmerend.subtract(slice_begin);
        }

        BigInteger slice_end = cur_begin.add(slice_width).subtract(BigInteger.ONE);

        KmerRangePartition slice = new KmerRangePartition(this.kmerSize, this.numPartitions, i, slice_width,
                slice_begin, slice_end);
        partitions[i] = slice;

        cur_begin = cur_begin.add(slice_width);
    }

    return partitions;
}

From source file:st.brothas.mtgoxwidget.MtGoxWidgetProvider.java

private static String round(Double value) {
    if (value == null) {
        return "N/A";
    }//  w  w w.  j a  v a  2 s .  c  om

    int decimals = 2;
    if (value >= 1000) {
        decimals = 0;
    } else if (value >= 100) {
        decimals = 1;
    }

    return BigDecimal.valueOf(value).setScale(decimals, BigDecimal.ROUND_HALF_UP).toString();
}

From source file:net.drgnome.virtualpack.util.Util.java

public static String printDoublePlain(double d) {
        return BigDecimal.valueOf(d).toPlainString();
    }

From source file:org.sfs.nodes.compute.container.GetContainer.java

@Override
public void handle(final SfsRequest httpServerRequest) {

    VertxContext<Server> vertxContext = httpServerRequest.vertxContext();
    aVoid().flatMap(new Authenticate(httpServerRequest))
            .flatMap(new ValidateActionAuthenticated(httpServerRequest))
            .map(aVoid -> fromSfsRequest(httpServerRequest)).map(new ValidateContainerPath())
            .flatMap(new LoadAccountAndContainer(vertxContext))
            .flatMap(new ValidateActionContainerListObjects(httpServerRequest)).flatMap(persistentContainer -> {

                HttpServerResponse httpServerResponse = httpServerRequest.response();

                MultiMap queryParams = httpServerRequest.params();
                MultiMap headerParams = httpServerRequest.headers();

                String format = queryParams.get(FORMAT);
                String accept = headerParams.get(ACCEPT);

                MediaType parsedAccept = null;

                if (equalsIgnoreCase("xml", format)) {
                    parsedAccept = APPLICATION_XML_UTF_8;
                } else if (equalsIgnoreCase("json", format)) {
                    parsedAccept = JSON_UTF_8;
                }//from  ww w  .ja  v a  2  s .  c o m

                if (parsedAccept == null) {
                    if (!isNullOrEmpty(accept)) {
                        parsedAccept = parse(accept);
                    }
                }

                if (parsedAccept == null || (!PLAIN_TEXT_UTF_8.is(parsedAccept)
                        && !APPLICATION_XML_UTF_8.is(parsedAccept) && !JSON_UTF_8.equals(parsedAccept))) {
                    parsedAccept = PLAIN_TEXT_UTF_8;
                }

                Observable<Optional<ContainerStats>> oContainerStats;
                boolean hasPrefix = !Strings.isNullOrEmpty(queryParams.get(SfsHttpQueryParams.PREFIX));
                if (hasPrefix) {
                    oContainerStats = just(persistentContainer)
                            .flatMap(new LoadContainerStats(httpServerRequest.vertxContext()))
                            .map(Optional::of);
                } else {
                    oContainerStats = Defer.just(Optional.<ContainerStats>absent());
                }

                Observable<ObjectList> oObjectListing = just(persistentContainer)
                        .flatMap(new ListObjects(httpServerRequest));

                MediaType finalParsedAccept = parsedAccept;
                return combineSinglesDelayError(oContainerStats, oObjectListing,
                        (containerStats, objectList) -> {

                            if (containerStats.isPresent()) {

                                Metadata metadata = persistentContainer.getMetadata();

                                for (String key : metadata.keySet()) {
                                    SortedSet<String> values = metadata.get(key);
                                    if (values != null && !values.isEmpty()) {
                                        httpServerResponse.putHeader(
                                                format("%s%s", X_ADD_CONTAINER_META_PREFIX, key), values);
                                    }
                                }

                                httpServerResponse.putHeader(X_CONTAINER_OBJECT_COUNT,
                                        valueOf(containerStats.get().getObjectCount()));
                                httpServerResponse.putHeader(X_CONTAINER_BYTES_USED,
                                        BigDecimal.valueOf(containerStats.get().getBytesUsed())
                                                .setScale(0, ROUND_HALF_UP).toString());
                            }

                            BufferOutputStream bufferOutputStream = new BufferOutputStream();

                            if (JSON_UTF_8.is(finalParsedAccept)) {

                                try {
                                    JsonFactory jsonFactory = vertxContext.verticle().jsonFactory();
                                    JsonGenerator jg = jsonFactory.createGenerator(bufferOutputStream, UTF8);
                                    jg.writeStartArray();

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        jg.writeStartObject();
                                        jg.writeStringField("hash",
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        jg.writeStringField("last_modified",
                                                toDateTimeString(listedObject.getLastModified()));
                                        jg.writeNumberField("bytes", listedObject.getLength());
                                        jg.writeStringField("content_type", listedObject.getContentType());
                                        jg.writeStringField("name", listedObject.getName());
                                        jg.writeEndObject();
                                    }

                                    jg.writeEndArray();
                                    jg.close();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }

                            } else if (APPLICATION_XML_UTF_8.is(finalParsedAccept)) {

                                String charset = UTF_8.toString();
                                XMLStreamWriter writer = null;
                                try {
                                    writer = newFactory().createXMLStreamWriter(bufferOutputStream, charset);

                                    writer.writeStartDocument(charset, "1.0");

                                    writer.writeStartElement("container");

                                    writer.writeAttribute("name",
                                            fromPaths(persistentContainer.getId()).containerName().get());

                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {

                                        writer.writeStartElement("object");

                                        writer.writeStartElement("name");
                                        writer.writeCharacters(listedObject.getName());
                                        writer.writeEndElement();

                                        writer.writeStartElement("hash");
                                        writer.writeCharacters(
                                                base16().lowerCase().encode(listedObject.getEtag()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("bytes");
                                        writer.writeCharacters(valueOf(listedObject.getLength()));
                                        writer.writeEndElement();

                                        writer.writeStartElement("content_type");
                                        writer.writeCharacters(listedObject.getContentType());
                                        writer.writeEndElement();

                                        writer.writeStartElement("last_modified");
                                        writer.writeCharacters(
                                                toDateTimeString(listedObject.getLastModified()));
                                        writer.writeEndElement();

                                        writer.writeEndElement();
                                    }

                                    writer.writeEndElement();

                                    writer.writeEndDocument();

                                } catch (XMLStreamException e) {
                                    throw new RuntimeException(e);
                                } finally {
                                    try {
                                        if (writer != null) {
                                            writer.close();
                                        }
                                    } catch (XMLStreamException e) {
                                        LOGGER.warn(e.getLocalizedMessage(), e);
                                    }
                                }

                            } else {
                                String charset = UTF_8.toString();
                                try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                                        bufferOutputStream, charset)) {
                                    for (ListedObject listedObject : ordered(objectList.getObjects())) {
                                        outputStreamWriter.write(listedObject.getName());
                                        outputStreamWriter.write("\n");
                                    }
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            objectList.clear();
                            return bufferOutputStream;
                        }).flatMap(bufferOutputStream -> {
                            Buffer buffer = bufferOutputStream.toBuffer();
                            httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, finalParsedAccept.toString())
                                    .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length()));
                            return AsyncIO.append(buffer, httpServerRequest.response());
                        });
            }).single().subscribe(new ConnectionCloseTerminus<Void>(httpServerRequest) {
                @Override
                public void onNext(Void aVoid) {

                }
            }

    );

}

From source file:cz.muni.fi.pv168.airshipmanager.ContractManagerImplTest.java

private Airship buildAirship(int diff) {
    Airship a = new Airship().setName("Testship " + Integer.toString(diff))
            .setPricePerDay(BigDecimal.valueOf(diff * 5)).setCapacity(diff * 4);
    airships.addAirship(a);// w  ww  .jav  a  2 s .  c  o  m
    return a;
}

From source file:net.javacrumbs.jsonunit.spring.JsonUnitResultMatchers.java

/**
 * Sets the tolerance for floating number comparison. If set to null, requires exact match of the values.
 * For example, if set to 0.01, ignores all differences lower than 0.01, so 1 and 0.9999 are considered equal.
 *//*from   www . j a va 2s  .co  m*/
public JsonUnitResultMatchers withTolerance(double tolerance) {
    return withTolerance(BigDecimal.valueOf(tolerance));
}