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.b2international.index.SortIndexTest.java

@Test
public void sortBigDecimalField() throws Exception {
    final PrimitiveIterator.OfDouble doubleIterator = new Random().doubles().iterator();
    final TreeSet<BigDecimal> orderedItems = newTreeSet();
    final Map<String, Data> documents = newHashMap();

    for (int i = 0; i < NUM_DOCS; i++) {
        BigDecimal item = null;// w w w  .jav a2s .  c o  m
        while (item == null || orderedItems.contains(item)) {
            item = BigDecimal.valueOf(doubleIterator.nextDouble());
        }
        orderedItems.add(item);

        final Data data = new Data();
        data.setBigDecimalField(item);
        documents.put(Integer.toString(i), data);
    }

    indexDocuments(documents);

    final Query<Data> ascendingQuery = Query.select(Data.class).where(Expressions.matchAll()).limit(NUM_DOCS)
            .sortBy(SortBy.field("bigDecimalField", Order.ASC)).build();

    checkDocumentOrder(ascendingQuery, data -> data.getBigDecimalField(), orderedItems, BigDecimal.class);

    final Query<Data> descendingQuery = Query.select(Data.class).where(Expressions.matchAll()).limit(NUM_DOCS)
            .sortBy(SortBy.field("bigDecimalField", Order.DESC)).build();

    checkDocumentOrder(descendingQuery, data -> data.getBigDecimalField(), orderedItems.descendingSet(),
            BigDecimal.class);
}

From source file:com.trenako.entities.Money.java

@Override
public String toString() {
    if (this == EMPTY_VALUE) {
        return "-";
    }//from  www.j  a  v  a 2s.co  m

    BigDecimal v = BigDecimal.valueOf(getValue()).divide(MONEY_VALUE_FACTOR);

    NumberFormat nf = NumberFormat.getCurrencyInstance();

    // the user may have selected a different currency than the default
    Currency currency = Currency.getInstance(getCurrency());
    nf.setCurrency(currency);
    nf.setMinimumFractionDigits(2);

    return nf.format(v);
}

From source file:org.tylproject.data.mongo.ModelTests.java

@Before
public void init() {
    //TylContext.setCurrentUser(Signature.of("mp@marcopancotti.it"));
    countryRep.deleteAll();/*w w w .j  av a 2 s. c  o  m*/
    languageRep.deleteAll();
    sistemOfUnitsRep.deleteAll();
    unitRep.deleteAll();
    convFactRep.deleteAll();
    numeratorTypeRep.deleteAll();
    numeratorRep.deleteAll();

    Country addedCountry = countryRep.save(new Country("it", "Italia", 123));
    addedCountry.setNumericCode(24);
    countryRep.save(addedCountry);
    addedCountry.setNumericCode(123);
    countryRep.save(addedCountry);

    Language language = new Language("it", "Italian");
    mongoTemplate.insert(language);
    language.setName("Italiano");
    mongoTemplate.save(language);
    Language english = new Language("en", "English");
    mongoTemplate.insert(english);

    NumeratorType invoiceType = new NumeratorType("invoiceType", mlTextOf("Invoice"));
    mongoTemplate.insert(invoiceType);
    NumeratorType salesOrderType = new NumeratorType("salesOrderType", mlTextOf("Sales Order"));
    mongoTemplate.insert(salesOrderType);
    Numerator invoiceNumerator = new Numerator("invNum", mlTextOf("Invoice Numerator"), invoiceType);
    NumeratorFeeder inv2014 = new NumeratorFeeder(new DateTime(2014, 1, 1, 0, 0),
            new DateTime(2014, 12, 31, 23, 59));
    inv2014.setLastNumberUsed(233);
    invoiceNumerator.getNumeratorFeeders().add(inv2014);
    NumeratorFeeder inv2015 = new NumeratorFeeder(new DateTime(2015, 1, 1, 0, 0),
            new DateTime(2015, 12, 31, 23, 59));
    invoiceNumerator.getNumeratorFeeders().add(inv2015);
    NumeratorFeeder inv2016 = new NumeratorFeeder(new DateTime(2016, 1, 1, 0, 0),
            new DateTime(2016, 12, 31, 23, 59));
    invoiceNumerator.getNumeratorFeeders().add(inv2016);
    mongoTemplate.insert(invoiceNumerator);

    MlText si = mlTextOf("International System of Units");
    si.setText(LangKey.it, "Unit di Misura Internazionale");
    si.setText(LangKey.es, "Unitad de Misuras");
    SystemOfUnits systemOfUnits = new SystemOfUnits("SI", si);
    mongoTemplate.insert(systemOfUnits);

    MlText unitName = mlTextOf("meter");
    Unit m = new Unit("m", unitName, systemOfUnits);
    Unit km = new Unit("km", unitName, systemOfUnits);
    mongoTemplate.insert(m);
    mongoTemplate.insert(km);
    mongoTemplate.insert(new ConversionFactor(km, m, BigDecimal.valueOf(1000)));
}

From source file:es.tid.fiware.rss.ws.RSSModelServiceTest.java

/**
 * // w w w.  j  ava2 s  .  c  om
 * @throws Exception
 */
@Test
public void updateRSSModel() throws Exception {
    RSSModel rssModel = new RSSModel();
    rssModel.setAppProviderId("appProviderId");
    rssModel.setProductClass("productClass");
    rssModel.setPercRevenueShare(BigDecimal.valueOf(30));
    Mockito.when(rssModelsManager.createRssModel("mail@mail.com", rssModel)).thenReturn(rssModel);
    Response response = rssModelService.modifyRSSModel("authToken", rssModel);
    Assert.assertEquals(201, response.getStatus());
}

From source file:com.github.nginate.commons.testing.Unique.java

/**
 * Generate unique bigdecimal from unique long
 *
 * @return unique bigdecimal//from w  w  w .j a  v  a2  s . c o  m
 * @see BigDecimal#valueOf(long)
 */
@Nonnull
public static BigDecimal uniqueBigDecimal() {
    return BigDecimal.valueOf(uniqueLong());
}

From source file:edu.emory.cci.aiw.cvrg.eureka.services.conversion.FrequencyFirstNotConsecutiveValueThresholdConverterTest.java

@Before
public void setUp() {
    PropositionDefinitionConverterVisitor converterVisitor = this
            .getInstance(PropositionDefinitionConverterVisitor.class);
    FrequencyValueThresholdConverter converter = new FrequencyValueThresholdConverter();
    converter.setConverterVisitor(converterVisitor);
    SystemProposition primParam = new SystemProposition();
    primParam.setId(1L);/*from  w ww  .  j  a  va  2 s  . co  m*/
    primParam.setKey("test-primparam1");
    primParam.setInSystem(true);
    primParam.setSystemType(SystemType.PRIMITIVE_PARAMETER);

    ValueThresholdGroupEntity thresholdGroup = new ValueThresholdGroupEntity();
    thresholdGroup.setId(2L);
    thresholdGroup.setKey("test-valuethreshold");
    thresholdGroupKey = thresholdGroup.getKey();

    ValueComparator lt = new ValueComparator();
    lt.setName("<");
    ValueComparator gt = new ValueComparator();
    gt.setName(">");
    ValueComparator lte = new ValueComparator();
    lte.setName("<=");
    ValueComparator gte = new ValueComparator();
    gte.setName(">=");
    lt.setComplement(gte);
    gte.setComplement(lt);
    gt.setComplement(lte);
    lte.setComplement(gt);

    ValueThresholdEntity threshold = new ValueThresholdEntity();
    threshold.setAbstractedFrom(primParam);
    threshold.setMinValueThreshold(BigDecimal.valueOf(100));
    threshold.setMinValueComp(gt);
    threshold.setMaxValueThreshold(BigDecimal.valueOf(200));
    threshold.setMaxValueComp(lt);
    threshold.setId(Long.valueOf(1));

    List<ValueThresholdEntity> thresholds = new ArrayList<>();
    thresholds.add(threshold);
    thresholdGroup.setValueThresholds(thresholds);

    TimeUnit dayUnit = new TimeUnit();
    dayUnit.setName("day");

    FrequencyType ft = new FrequencyType();
    ft.setName("first");

    frequency = new FrequencyEntity();
    frequency.setId(3L);
    frequency.setKey("test-freqhla-key");
    frequency.setCount(2);
    frequency.setWithinAtLeast(1);
    frequency.setWithinAtLeastUnits(dayUnit);
    frequency.setWithinAtMost(90);
    frequency.setWithinAtMostUnits(dayUnit);
    frequency.setFrequencyType(ft);

    ExtendedPhenotype af = new ExtendedPhenotype();
    af.setPhenotypeEntity(thresholdGroup);
    frequency.setExtendedProposition(af);

    propDefs = converter.convert(frequency);

    llas = new ArrayList<>();
    for (PropositionDefinition propDef : propDefs) {
        if (propDef instanceof LowLevelAbstractionDefinition) {
            llas.add((LowLevelAbstractionDefinition) propDef);
        }
    }
    llaDef = llas.get(0);
    hlad = converter.getPrimaryPropositionDefinition();

    userConstraintName = asValueString(thresholdGroupKey);
    compConstraintName = asValueCompString(thresholdGroupKey);

    tepd = (TemporalExtendedPropositionDefinition) hlad.getExtendedPropositionDefinitions().iterator().next();

    gf = (SimpleGapFunction) hlad.getGapFunction();
}

From source file:edu.emory.cci.aiw.cvrg.eureka.services.conversion.FrequencyAtLeastNotConsecutiveValueThresholdConverterTest.java

@Before
public void setUp() {
    PropositionDefinitionConverterVisitor converterVisitor = this
            .getInstance(PropositionDefinitionConverterVisitor.class);
    FrequencyValueThresholdConverter converter = new FrequencyValueThresholdConverter();
    converter.setConverterVisitor(converterVisitor);
    SystemProposition primParam = new SystemProposition();
    primParam.setId(1L);//from   ww w .  ja v  a2 s  .com
    primParam.setKey("test-primparam1");
    primParam.setInSystem(true);
    primParam.setSystemType(SystemType.PRIMITIVE_PARAMETER);

    ValueThresholdGroupEntity thresholdGroup = new ValueThresholdGroupEntity();
    thresholdGroup.setId(2L);
    thresholdGroup.setKey("test-valuethreshold");
    thresholdGroupKey = thresholdGroup.getKey();

    ValueComparator lt = new ValueComparator();
    lt.setName("<");
    ValueComparator gt = new ValueComparator();
    gt.setName(">");
    ValueComparator lte = new ValueComparator();
    lte.setName("<=");
    ValueComparator gte = new ValueComparator();
    gte.setName(">=");
    lt.setComplement(gte);
    gte.setComplement(lt);
    gt.setComplement(lte);
    lte.setComplement(gt);

    ValueThresholdEntity threshold = new ValueThresholdEntity();
    threshold.setAbstractedFrom(primParam);
    threshold.setMinValueThreshold(BigDecimal.valueOf(100));
    threshold.setMinValueComp(gt);
    threshold.setMaxValueThreshold(BigDecimal.valueOf(200));
    threshold.setMaxValueComp(lt);
    threshold.setId(Long.valueOf(1));

    List<ValueThresholdEntity> thresholds = new ArrayList<>();
    thresholds.add(threshold);
    thresholdGroup.setValueThresholds(thresholds);

    TimeUnit dayUnit = new TimeUnit();
    dayUnit.setName("day");

    FrequencyType ft = new FrequencyType();
    ft.setName("at least");

    frequency = new FrequencyEntity();
    frequency.setId(3L);
    frequency.setKey("test-freqhla-key");
    frequency.setCount(2);
    frequency.setWithinAtLeast(1);
    frequency.setWithinAtLeastUnits(dayUnit);
    frequency.setWithinAtMost(90);
    frequency.setWithinAtMostUnits(dayUnit);
    frequency.setFrequencyType(ft);

    ExtendedPhenotype af = new ExtendedPhenotype();
    af.setPhenotypeEntity(thresholdGroup);
    frequency.setExtendedProposition(af);

    propDefs = converter.convert(frequency);

    llas = new ArrayList<>();
    for (PropositionDefinition propDef : propDefs) {
        if (propDef instanceof LowLevelAbstractionDefinition) {
            llas.add((LowLevelAbstractionDefinition) propDef);
        }
    }
    llaDef = llas.get(0);
    hlad = converter.getPrimaryPropositionDefinition();

    userConstraintName = asValueString(thresholdGroupKey);
    compConstraintName = asValueCompString(thresholdGroupKey);

    tepd = (TemporalExtendedParameterDefinition) hlad.getExtendedPropositionDefinitions().iterator().next();

    gf = (SimpleGapFunction) hlad.getGapFunction();
}

From source file:com.ar.dev.tierra.api.controller.DetalleFacturaController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> add(OAuth2Authentication authentication, @RequestParam("idFactura") int idFactura,
        @RequestParam("idProducto") int idProducto, @RequestParam("idItem") int idItem,
        @RequestParam("cantidadItem") int cantidadItem) {
    /*Instancia de nuevo detalle*/
    DetalleFactura detalleFactura = new DetalleFactura();
    /*Traemos los objectos necesarios para aadir el detalle*/
    Usuarios user = facadeService.getUsuariosDAO().findUsuarioByUsername(authentication.getName());
    Producto prod = facadeService.getProductoDAO().findById(idProducto);
    WrapperStock stock = facadeService.getStockDAO().searchStockById(idItem,
            user.getUsuarioSucursal().getIdSucursal());
    Factura factura = facadeService.getFacturaDAO().searchById(idFactura);
    /*Bandera de control*/
    boolean control = false;
    /*Variable de calculo de cantidad*/
    @SuppressWarnings("UnusedAssignment")
    int cantidadStock = 0;

    detalleFactura.setUsuarioCreacion(user.getIdUsuario());
    detalleFactura.setFechaCreacion(new Date());
    detalleFactura.setEstadoDetalle(true);

    if (prod.getCantidadTotal() >= cantidadItem) {
        if (stock.getStockTierra() != null) {
            if (stock.getStockTierra().getCantidad() >= cantidadItem) {
                cantidadStock = stock.getStockTierra().getCantidad() - cantidadItem;
                stock.getStockTierra().setCantidad(cantidadStock);
                control = true;//from  w  w  w.jav  a2s.c  o  m
            }
        }
        if (stock.getStockBebelandia() != null) {
            if (stock.getStockBebelandia().getCantidad() >= cantidadItem) {
                cantidadStock = stock.getStockBebelandia().getCantidad() - cantidadItem;
                stock.getStockBebelandia().setCantidad(cantidadStock);
                control = true;
            }
        }
        if (stock.getStockLibertador() != null) {
            if (stock.getStockLibertador().getCantidad() >= cantidadItem) {
                cantidadStock = stock.getStockLibertador().getCantidad() - cantidadItem;
                stock.getStockLibertador().setCantidad(cantidadStock);
                control = true;
            }
        }
        if (control) {
            int cantidadTotal = prod.getCantidadTotal();
            /*seteamos cantidad nueva de productos*/
            prod.setCantidadTotal(cantidadTotal - cantidadItem);
            /*seteamos producto en el detalle*/
            detalleFactura.setProducto(prod);
            /*Calculamos el total del detalle*/
            BigDecimal monto = detalleFactura.getProducto().getPrecioVenta()
                    .multiply(BigDecimal.valueOf(cantidadItem));
            /*seteamos el total del detalle*/
            detalleFactura.setTotalDetalle(monto);
            /*seteamos la factura del detalle*/
            detalleFactura.setFactura(factura);
            /*seteamos descuento en cero*/
            detalleFactura.setDescuentoDetalle(BigDecimal.ZERO);
            /*seteamos la cantidad de items en el detalle*/
            detalleFactura.setCantidadDetalle(cantidadItem);
            /*Indicamos el idStock del detalle*/
            detalleFactura.setIdStock(idItem);
            /*Actualizamos producto*/
            facadeService.getProductoDAO().update(prod);
            /*Actualizamos el stock*/
            facadeService.getStockDAO().update(stock);
            /*Insertamos el nuevo detalle*/
            facadeService.getDetalleFacturaDAO().add(detalleFactura);
            /*Traemos lista de detalles, calculamos su nuevo total y actualizamos*/
            List<DetalleFactura> detallesFactura = facadeService.getDetalleFacturaDAO()
                    .facturaDetalle(idFactura);
            BigDecimal sumMonto = new BigDecimal(BigInteger.ZERO);
            for (DetalleFactura detailList : detallesFactura) {
                sumMonto = sumMonto.add(detailList.getTotalDetalle());
            }
            factura.setTotal(sumMonto);
            factura.setFechaModificacion(new Date());
            factura.setUsuarioModificacion(user.getIdUsuario());
            facadeService.getFacturaDAO().update(factura);
            JsonResponse msg = new JsonResponse("Success", "Detalle agregado con exito");
            return new ResponseEntity<>(msg, HttpStatus.OK);
        } else {
            JsonResponse msg = new JsonResponse("Error", "Stock insuficiente.");
            return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
        }
    } else {
        JsonResponse msg = new JsonResponse("Error", "Stock insuficiente.");
        return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
    }
}

From source file:com.aan.girsang.server.service.impl.TransaksiServiceImpl.java

@Transactional(isolation = Isolation.SERIALIZABLE)
@Override//from www  .ja v a 2 s  .c om
public void simpan(Pembelian p) {
    Pembelian pembelian = pembelianDao.cariId(p.getNoRef());
    if (pembelian == null) {
        p.setNoRef(runningNumberTransaksiDao.ambilBerikutnyaDanSimpan(TransaksiRunningNumberEnum.PEMBELIAN));
        int i = 1;
        for (PembelianDetail detail : p.getPembelianDetails()) {
            detail.setId(p.getNoRef() + i++);
        }
    } else {
        int i = 1;
        for (PembelianDetail detail : p.getPembelianDetails()) {
            try {
                i++;
                if (detail.getId() == null) {
                    detail.setId(p.getNoRef() + i++);
                }
            } catch (Exception e) {
                i = i + 1;
                if (detail.getId() == null) {
                    detail.setId(p.getNoRef() + i++);
                }
            }
            if (detail.getId() == null) {
                detail.setId(p.getNoRef() + i++);
            }
        }
    }
    //update barang
    //<editor-fold defaultstate="collapsed" desc="Update Barang">
    for (PembelianDetail detail : p.getPembelianDetails()) {

        Barang b = barangDao.cariId(detail.getBarang().getPlu());
        if (detail.getUpdate() == true) {
            Double hargaBeli = Double.valueOf(TextComponentUtils
                    .getValueFromTextNumber(TextComponentUtils.formatNumber(detail.getHargaBarang())));
            Double isi = Double.valueOf(detail.getIsiPembelian());//harga beli di bagi isi
            Double hargaSatuan = hargaBeli / isi;
            BigDecimal hS = new BigDecimal(hargaSatuan, MathContext.DECIMAL64);
            b.setSatuanPembelian(detail.getSatuanPembelian());
            b.setHargaBeli(BigDecimal.valueOf(hargaSatuan));
            b.setIsiPembelian(detail.getIsiPembelian());

            //Simpan HPP Barang
            HPPBarang hPPBarang = new HPPBarang();
            hPPBarang.setIdHpp(runningNumberDao.ambilBerikutnyaDanSimpan(MasterRunningNumberEnum.HPP));
            hPPBarang.setTanggal(detail.getPembelian().getTanggal());
            hPPBarang.setBarang(b);
            hPPBarang.setHpp(detail.getHargaBarang());
            hPPBarang.setIsi(detail.getIsiPembelian());
            hPPBarang.setHppSatuan(BigDecimal.valueOf(hargaSatuan));

            barangDao.simpan(b);
            hPPDao.simpan(hPPBarang);
        }

    }
    //</editor-fold>
    pembelianDao.merge(p);
    simpanStokPembelian(p);
    simpanHutang();
}

From source file:edu.emory.cci.aiw.cvrg.eureka.services.conversion.FrequencyAtLeastConsecutiveValueThresholdConverterTest.java

@Before
public void setUp() {
    PropositionDefinitionConverterVisitor converterVisitor = this
            .getInstance(PropositionDefinitionConverterVisitor.class);
    FrequencyValueThresholdConverter converter = new FrequencyValueThresholdConverter();
    converter.setConverterVisitor(converterVisitor);
    SystemProposition primParam = new SystemProposition();
    primParam.setId(1L);/*from ww  w .j av  a  2s .c  om*/
    primParam.setKey("test-primparam1");
    primParam.setInSystem(true);
    primParam.setSystemType(SystemType.PRIMITIVE_PARAMETER);

    ValueThresholdGroupEntity thresholdGroup = new ValueThresholdGroupEntity();
    thresholdGroup.setId(2L);
    thresholdGroup.setKey("test-valuethreshold");
    thresholdGroupKey = thresholdGroup.getKey();

    ValueComparator lt = new ValueComparator();
    lt.setName("<");
    ValueComparator gt = new ValueComparator();
    gt.setName(">");
    ValueComparator lte = new ValueComparator();
    lte.setName("<=");
    ValueComparator gte = new ValueComparator();
    gte.setName(">=");
    lt.setComplement(gte);
    gte.setComplement(lt);
    gt.setComplement(lte);
    lte.setComplement(gt);

    ValueThresholdEntity threshold = new ValueThresholdEntity();
    threshold.setAbstractedFrom(primParam);
    threshold.setMinValueThreshold(BigDecimal.valueOf(100));
    threshold.setMinValueComp(gt);
    threshold.setMaxValueThreshold(BigDecimal.valueOf(200));
    threshold.setMaxValueComp(lt);
    threshold.setId(Long.valueOf(1));

    List<ValueThresholdEntity> thresholds = new ArrayList<>();
    thresholds.add(threshold);
    thresholdGroup.setValueThresholds(thresholds);

    TimeUnit dayUnit = new TimeUnit();
    dayUnit.setName("day");

    FrequencyType ft = new FrequencyType();
    ft.setName("at least");

    frequency = new FrequencyEntity();
    frequency.setId(3L);
    frequency.setKey("test-freqhla-key");
    frequency.setCount(2);
    frequency.setWithinAtLeast(1);
    frequency.setWithinAtLeastUnits(dayUnit);
    frequency.setWithinAtMost(90);
    frequency.setWithinAtMostUnits(dayUnit);
    frequency.setFrequencyType(ft);
    frequency.setConsecutive(true);

    ExtendedPhenotype af = new ExtendedPhenotype();
    af.setPhenotypeEntity(thresholdGroup);
    frequency.setExtendedProposition(af);

    propDefs = converter.convert(frequency);

    llas = new ArrayList<>();
    for (PropositionDefinition propDef : propDefs) {
        if (propDef instanceof LowLevelAbstractionDefinition) {
            llas.add((LowLevelAbstractionDefinition) propDef);
        }
    }
    llaDef = llas.get(0);
    hlad = converter.getPrimaryPropositionDefinition();

    userConstraintName = asValueString(thresholdGroupKey);
    compConstraintName = asValueCompString(thresholdGroupKey);

    tepd = (TemporalExtendedParameterDefinition) hlad.getExtendedPropositionDefinitions().iterator().next();

    gf = (SimpleGapFunction) hlad.getGapFunction();
}