Example usage for java.math MathContext DECIMAL128

List of usage examples for java.math MathContext DECIMAL128

Introduction

In this page you can find the example usage for java.math MathContext DECIMAL128.

Prototype

MathContext DECIMAL128

To view the source code for java.math MathContext DECIMAL128.

Click Source Link

Document

A MathContext object with a precision setting matching the IEEE 754R Decimal128 format, 34 digits, and a rounding mode of RoundingMode#HALF_EVEN HALF_EVEN , the IEEE 754R default.

Usage

From source file:com.marcosanta.service.impl.KalturaServiceImpl.java

@Override
public ReporteGeneralGranulado topTen(Date fechaInicio, Date fechaFin, String valorUnitarioTam,
        String valorUnitarioTiempoVisto, int novistos) {
    BigDecimal total = new BigDecimal(0);
    ReporteGeneralGranulado rpg = new ReporteGeneralGranulado();
    List<SistemaSubReporte> ssr;
    List<CatReporteXls> ssrCompleta = new ArrayList<>();
    CatReporteXls top[] = new CatReporteXls[11];
    for (int i = 0; i < 11; i++) {
        top[i] = new CatReporteXls();
    }/*from   w ww.  jav a2  s .co m*/
    for (KalturaCuenta kc : consultasBDService.findAllCuenta()) {
        for (KalturaUnidad ku : kc.getListaUnidad()) {
            for (KalturaFabrica kf : ku.getListaFabricas()) {
                if (fechaInicio != null && fechaFin != null) {
                    ssr = consultasBDService.findSubReportByFechaCorteNivelPrograma(fechaInicio, fechaFin,
                            "programa", kc.getNombre(), kf.getNombre(), novistos);
                } else {
                    ssr = consultasBDService.findReportNivelPrograma("programa", kc.getNombre(), kf.getNombre(),
                            novistos);
                }
                for (SistemaSubReporte subReporte : ssr) {
                    total = total.add(new BigDecimal(subReporte.getTiempoVisto()));
                    if (ssrCompleta.contains(new CatReporteXls(subReporte.getNombre()))) {
                        CatReporteXls caRepTmp = ssrCompleta
                                .get(ssrCompleta.indexOf(new CatReporteXls(subReporte.getNombre())));
                        if (caRepTmp.getNombreFabrica().equals(kf.getNombre())
                                && caRepTmp.getNombreUnidad().equals(ku.getNombre())) {
                            caRepTmp.setMinVistos(
                                    caRepTmp.getMinVistos().add(new BigDecimal(subReporte.getTiempoVisto())));
                            caRepTmp.setMinVisUni(
                                    caRepTmp.getMinVisUni().add(new BigDecimal((subReporte.getTiempoVisto()
                                            * Double.parseDouble(valorUnitarioTiempoVisto)))));
                        } else {
                            ssrCompleta.add(new CatReporteXls(subReporte.getNombre(),
                                    new BigDecimal(subReporte.getTiempoVisto()),
                                    new BigDecimal(subReporte.getTiempoVisto()
                                            * Double.parseDouble(valorUnitarioTiempoVisto)),
                                    subReporte.getUnidad(), subReporte.getFabrica()));
                        }
                    } else {
                        ssrCompleta.add(new CatReporteXls(subReporte.getNombre(),
                                new BigDecimal(subReporte.getTiempoVisto()),
                                new BigDecimal(subReporte.getTiempoVisto()
                                        * Double.parseDouble(valorUnitarioTiempoVisto)),
                                subReporte.getUnidad(), subReporte.getFabrica()));
                    }
                }
            }
        }
    }

    for (CatReporteXls crx : ssrCompleta) {
        for (int i = 0; i < 10; i++) {
            if (crx.getMinVistos().compareTo(top[i].getMinVistos()) == 1) {
                if (i < 9 && top[i + 1].getMinVistos().compareTo(crx.getMinVistos()) == -1) {
                } else {
                    top[i] = crx;
                    break;
                }
            }
        }
    }
    List<CatReporteXls> ssrCompletas = new ArrayList<>();
    for (int i = 9; i >= 0; i--) {
        top[i].setPorciento(
                top[i].getMinVistos().multiply(new BigDecimal(100).divide(total, MathContext.DECIMAL128)));
        ssrCompletas.add(top[i]);
        System.out.println(top[i].getNombre() + " " + top[i].getMinVistos() + " " + top[i].getMinVisUni() + " "
                + top[i].getPorciento());
    }
    rpg.setTabla(ssrCompletas);
    return rpg;
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * generate cosine factor for trigonometric functions in BigDecimal.
 *
 * @param mc {@link java.math.MathContext}.
 * @return list of cosine factors./* w  w  w .j a  v a  2s .c om*/
 */
private static List<BigDecimal> initCosineFactor(MathContext mc) {
    int precision = (mc == null ? MathContext.DECIMAL128 : mc).getPrecision();
    List<BigDecimal> factors = new ArrayList<BigDecimal>();
    BigDecimal divisor = BigDecimal.valueOf(2d);
    BigDecimal temporary = BigDecimal.valueOf(2d);
    do {
        factors.add(BigDecimal.ONE.divide(divisor, precision + 2, RoundingMode.HALF_UP));
        temporary = temporary.add(BigDecimal.ONE);
        divisor = divisor.multiply(temporary);
        temporary = temporary.add(BigDecimal.ONE);
        divisor = divisor.multiply(temporary);
    } while (factors.get(factors.size() - 1).compareTo(new BigDecimal("1E-" + (precision + 2))) > 0);

    return factors;
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * {@link Math#cos(double)} in {@link java.math.BigDecimal}.
 *
 * @param angle the angle represented by radians.
 * @param isRadians if false, the angle represented by degrees.
 * @return//ww w.  j a  v  a  2 s . co m
 */
public static BigDecimal cos(final BigDecimal n, boolean isRadians) {
    return cos(n, MathContext.DECIMAL128, isRadians);
}

From source file:jp.furplag.util.commons.NumberUtils.java

public static BigDecimal cos(final BigDecimal angle, MathContext mc, boolean isRadians) {
    if (angle == null)
        return null;
    BigDecimal cos = BigDecimal.ONE;
    BigDecimal radians = isRadians ? angle : valueOf(toRadians(angle), BigDecimal.class);
    BigDecimal nSquare = radians.pow(2);
    int index = 0;
    for (BigDecimal factor : COSINE_FACTOR_DECIMAL128) {
        BigDecimal temporary = factor.multiply(nSquare);
        if (index % 2 == 0)
            temporary = temporary.negate();
        cos = cos.add(temporary);//  w w w . j a  va 2 s  .c  om
        nSquare = nSquare.multiply(radians.pow(2)).setScale(
                ((mc == null ? MathContext.DECIMAL128 : mc).getPrecision() + 2), RoundingMode.HALF_UP);
        index++;
    }

    return cos.setScale((mc == null ? MathContext.DECIMAL128 : mc).getPrecision(), RoundingMode.HALF_UP);
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * {@code n / divisor}./*from   w w w. j a va  2 s  .c o m*/
 *
 * @param o the object, number or string.
 * @param divisor value by which 'o' is to be divided.
 * @param scale of the {@code n / divisor} quotient to be returned.
 * @param mode {@link java.math.RoundingMode}.
 * @param type return number type.
 * @return {@code (type) (o / divisor)}.
 */
public static <T extends Number> T divide(final Object o, final Number divisor, final Number scale,
        final RoundingMode mode, final Class<T> type) {
    if (type == null)
        return null;
    Number n = valueOf(o);
    if (n == null)
        return setScale(divisor, scale, mode, type);
    if (divisor == null)
        return setScale(n, scale, mode, type);
    MathContext mc = new MathContext(INFINITY_DOUBLE.precision(), RoundingMode.HALF_EVEN);
    if (ClassUtils.isPrimitiveOrWrappers(n, divisor, type))
        mc = MathContext.DECIMAL128;
    if (scale != null)
        return setScale(valueOf(n, BigDecimal.class).divide(valueOf(divisor, BigDecimal.class), mc), scale,
                mode, type);

    return NumberObject.of(type)
            .valueOf(valueOf(n, BigDecimal.class).divide(valueOf(divisor, BigDecimal.class), mc));
}

From source file:de.appsolve.padelcampus.utils.BookingUtil.java

public OfferDurationPrice getOfferDurationPrice(List<CalendarConfig> configs, List<Booking> confirmedBookings,
        LocalDate selectedDate, LocalTime selectedTime, Offer selectedOffer) throws CalendarConfigException {
    List<TimeSlot> timeSlotsForDate = getTimeSlotsForDate(selectedDate, configs, confirmedBookings,
            Boolean.TRUE, Boolean.TRUE);
    boolean validStartTime = false;
    for (TimeSlot timeSlot : timeSlotsForDate) {
        if (timeSlot.getStartTime().equals(selectedTime)) {
            validStartTime = true;//from   w  w  w  .  ja va  2 s  . c  om
            break;
        }
    }

    OfferDurationPrice offerDurationPrices = null;
    if (validStartTime) {
        //convert to required data structure
        Map<Offer, List<CalendarConfig>> offerConfigMap = new HashMap<>();
        for (CalendarConfig config : configs) {
            for (Offer offer : config.getOffers()) {
                if (offer.equals(selectedOffer)) {
                    List<CalendarConfig> list = offerConfigMap.get(offer);
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    list.add(config);

                    //sort by start time
                    Collections.sort(list);
                    offerConfigMap.put(offer, list);
                }
            }
        }

        Iterator<Map.Entry<Offer, List<CalendarConfig>>> iterator = offerConfigMap.entrySet().iterator();
        //for every offer
        while (iterator.hasNext()) {
            Map.Entry<Offer, List<CalendarConfig>> entry = iterator.next();
            Offer offer = entry.getKey();
            List<CalendarConfig> configsForOffer = entry.getValue();

            //make sure the first configuration starts before the requested booking time
            if (selectedTime.compareTo(configsForOffer.get(0).getStartTime()) < 0) {
                continue;
            }

            LocalDateTime endTime = null;
            Integer duration = configsForOffer.get(0).getMinDuration();
            BigDecimal pricePerMinute;
            BigDecimal price = null;
            CalendarConfig previousConfig = null;
            Map<Integer, BigDecimal> durationPriceMap = new TreeMap<>();
            Boolean isContiguous = true;
            for (CalendarConfig config : configsForOffer) {

                //make sure there is no gap between calendar configurations
                if (endTime == null) {
                    //first run
                    endTime = getLocalDateTime(selectedDate, selectedTime).plusMinutes(config.getMinDuration());
                } else {
                    //break if there are durations available and calendar configs are not contiguous
                    if (!durationPriceMap.isEmpty()) {
                        //we substract min interval before the comparison as it has been added during the last iteration
                        LocalDateTime configStartDateTime = getLocalDateTime(selectedDate,
                                config.getStartTime());
                        if (!endTime.minusMinutes(config.getMinInterval()).equals(configStartDateTime)) {
                            break;
                        }
                    }
                }

                Integer interval = config.getMinInterval();

                pricePerMinute = getPricePerMinute(config);

                //as long as the endTime is before the end time configured in the calendar
                LocalDateTime configEndDateTime = getLocalDateTime(selectedDate, config.getEndTime());
                while (endTime.compareTo(configEndDateTime) <= 0) {
                    TimeSlot timeSlot = new TimeSlot();
                    timeSlot.setDate(selectedDate);
                    timeSlot.setStartTime(selectedTime);
                    timeSlot.setEndTime(endTime.toLocalTime());
                    timeSlot.setConfig(config);
                    Long bookingSlotsLeft = getBookingSlotsLeft(timeSlot, offer, confirmedBookings);

                    //we only allow contiguous bookings for any given offer
                    if (bookingSlotsLeft < 1) {
                        isContiguous = false;
                        break;
                    }

                    if (price == null) {
                        //see if previousConfig endTime - minInterval matches the selected time. if so, take half of the previous config price as a basis
                        if (previousConfig != null && previousConfig.getEndTime()
                                .minusMinutes(previousConfig.getMinInterval()).equals(selectedTime)) {
                            BigDecimal previousConfigPricePerMinute = getPricePerMinute(previousConfig);
                            price = previousConfigPricePerMinute.multiply(
                                    new BigDecimal(previousConfig.getMinInterval()), MathContext.DECIMAL128);
                            price = price.add(pricePerMinute.multiply(
                                    new BigDecimal(duration - previousConfig.getMinInterval()),
                                    MathContext.DECIMAL128));
                        } else {
                            price = pricePerMinute.multiply(new BigDecimal(duration.toString()),
                                    MathContext.DECIMAL128);
                        }
                    } else {
                        //add price for additional interval
                        price = price.add(pricePerMinute.multiply(new BigDecimal(interval.toString()),
                                MathContext.DECIMAL128));
                    }
                    price = price.setScale(2, RoundingMode.HALF_EVEN);
                    durationPriceMap.put(duration, price);

                    //increase the duration by the configured minimum interval and determine the new end time for the next iteration
                    duration += interval;
                    endTime = endTime.plusMinutes(interval);
                }

                if (!durationPriceMap.isEmpty()) {
                    OfferDurationPrice odp = new OfferDurationPrice();
                    odp.setOffer(offer);
                    odp.setDurationPriceMap(durationPriceMap);
                    odp.setConfig(config);
                    offerDurationPrices = odp;
                }

                if (!isContiguous) {
                    //we only allow coniguous bookings for one offer. process next offer
                    break;
                }
                previousConfig = config;

            }
        }
    }
    return offerDurationPrices;
}

From source file:com.marcosanta.service.impl.KalturaServiceImpl.java

private int GeneraReporte(List<CatReporteXls> reporteGlobal, List<CatReporteXls> reporteEntrys,
        List<Object[]> objs, int totalentrys, String nombre, String valorUnitarioMIN, String valorUnitarioTam,
        String partnerId) {//w  w  w  .j a va 2  s . c  om
    for (Object[] obj : objs) {
        SistemaReporte sr = new SistemaReporte((String) obj[0], (int) obj[1], (long) obj[2]);
        sr.setDuracion(0L);
        sr.setFechaCorte(new Date());
        BigDecimal tamanioDeci = new BigDecimal(sr.getTamanio())
                .divide(new BigDecimal(1024), MathContext.DECIMAL128)
                .divide(new BigDecimal(1024), MathContext.DECIMAL128);
        BigDecimal taDeci = new BigDecimal(sr.getTamanio()).divide(new BigDecimal(1024), MathContext.DECIMAL128)
                .divide(new BigDecimal(1024), MathContext.DECIMAL128);
        if (reporteGlobal.contains(new CatReporteXls(nombre))) {
            reporteEntrys.add(new CatReporteXls(sr.getEntryId(), partnerId));
            CatReporteXls caRepTmp = reporteGlobal.get(reporteGlobal.indexOf(new CatReporteXls(nombre)));
            caRepTmp.setMinVistos(caRepTmp.getMinVistos().add(new BigDecimal(sr.getTiempoVisto())));
            caRepTmp.setDuration(caRepTmp.getDuration().add(new BigDecimal(sr.getDuracion())));
            caRepTmp.setTamanio(caRepTmp.getTamanio().add(tamanioDeci));
            caRepTmp.setTotalEntrys(new BigDecimal(totalentrys));
            caRepTmp.setTamUni(caRepTmp.getTamUni()
                    .add(tamanioDeci.multiply(new BigDecimal(Double.parseDouble(valorUnitarioTam)))));
            caRepTmp.setMinVisUni(caRepTmp.getMinVisUni().add(new BigDecimal(sr.getTiempoVisto())));
        } else {
            reporteEntrys.add(new CatReporteXls(sr.getEntryId(), partnerId));
            reporteGlobal.add(new CatReporteXls(nombre, new BigDecimal(sr.getTiempoVisto()), tamanioDeci,
                    new BigDecimal(sr.getDuracion()), sr.getFechaCorte(),
                    new BigDecimal(sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)),
                    new BigDecimal(tamanioDeci.floatValue() * Double.parseDouble(valorUnitarioTam)),
                    new BigDecimal(totalentrys)));

        }
        totalentrys++;
    }
    return totalentrys;
}

From source file:com.marcosanta.service.impl.KalturaServiceImpl.java

private int GeneraReporte2(List<CatReporteXls> reporteGlobal, List<Object[]> objs, int totalentrys,
        String nombre, String valorUnitarioMIN, String valorUnitarioTam, String cuenta) {
    for (Object[] obj : objs) {
        SistemaReporte sr = new SistemaReporte((String) obj[0], (Integer) obj[1], (long) obj[2], (long) obj[3],
                (String) obj[4], (String) obj[5], (String) obj[6], (Date) obj[7]);
        sr.setNombre(sr.getEntryId());/*  w w  w  .  j av  a  2s .c o m*/
        sr.setDuracion(0L);
        sr.setFechaCorte(new Date());
        BigDecimal tamanioDeci = new BigDecimal(sr.getTamanio())
                .divide(new BigDecimal(1024), MathContext.DECIMAL128)
                .divide(new BigDecimal(1024), MathContext.DECIMAL128);
        BigDecimal taDeci = new BigDecimal(sr.getTamanio()).divide(new BigDecimal(1024), MathContext.DECIMAL128)
                .divide(new BigDecimal(1024), MathContext.DECIMAL128);
        if (reporteGlobal.contains(new CatReporteXls(sr.getNombre()))) {
            CatReporteXls caRepTmp = reporteGlobal
                    .get(reporteGlobal.indexOf(new CatReporteXls(sr.getNombre())));
            caRepTmp.setMinVistos(caRepTmp.getMinVistos().add(new BigDecimal(sr.getTiempoVisto())));
            caRepTmp.setDuration(caRepTmp.getDuration().add(new BigDecimal(sr.getDuracion())));
            caRepTmp.setTamanio(caRepTmp.getTamanio().add(tamanioDeci));
            caRepTmp.setTotalEntrys(new BigDecimal(totalentrys));
            caRepTmp.setTamUni(caRepTmp.getTamUni()
                    .add(tamanioDeci.multiply(new BigDecimal(Double.parseDouble(valorUnitarioTam)))));
            caRepTmp.setMinVisUni(caRepTmp.getMinVisUni().add(new BigDecimal(sr.getTiempoVisto())));
        } else {
            reporteGlobal.add(new CatReporteXls(sr.getNombre(), sr.getNombre(), sr.getNombreFabrica(),
                    sr.getNombrePrograma(), cuenta, sr.getNombre(), sr.getNombreUnidad(), tamanioDeci,
                    new BigDecimal(sr.getDuracion()), new BigDecimal(sr.getTiempoVisto()), sr.getFechaCorte(),
                    sr.getFechaCreacion(),
                    new BigDecimal(sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)),
                    new BigDecimal(tamanioDeci.floatValue() * Double.parseDouble(valorUnitarioTam)),
                    new BigDecimal(totalentrys)));

        }
        totalentrys++;
    }
    return totalentrys;
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#floor(java.lang.Object, java.lang.Class)}.
 */// w w  w  .j a v a2 s .co  m
@SuppressWarnings("unchecked")
@Test
public void testFloorObjectClassOfT() {
    assertEquals("null", null, floor(null, null));
    assertEquals("null", null, floor("", null));
    assertEquals("null", null, floor("not a number.", null));
    for (Class<?> type : NUMBERS) {
        try {
            Object expected = null;
            Class<? extends Number> typeOfN = (Class<? extends Number>) type;
            Class<? extends Number> wrapper = (Class<? extends Number>) ClassUtils.primitiveToWrapper(type);
            if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getMethod("valueOf", String.class).invoke(null, "3");
            } else {
                Constructor<?> c = type.getDeclaredConstructor(String.class);
                expected = c.newInstance("3");
            }
            assertEquals("PI: String: " + type.getSimpleName(), expected, floor("3.14", typeOfN));
            assertEquals("PI: Float: " + type.getSimpleName(), expected, floor(3.141592653589793f, typeOfN));
            assertEquals("PI: Double: " + type.getSimpleName(), expected, floor(Math.PI, typeOfN));
            assertEquals("PI: BigDecimal: " + type.getSimpleName(), expected,
                    floor(BigDecimal.valueOf(Math.PI), typeOfN));
            assertEquals("(Double) (10 / 3): " + type.getSimpleName(), expected, floor(
                    (Object) (BigDecimal.TEN.divide(new BigDecimal("3"), MathContext.DECIMAL128)), typeOfN));
            if (ObjectUtils.isAny(wrapper, Double.class, Float.class)) {
                expected = wrapper.getField("POSITIVE_INFINITY").get(null);
            } else if (ClassUtils.isPrimitiveWrapper(wrapper)) {
                expected = wrapper.getField("MAX_VALUE").get(null);
                assertEquals("Huge: " + type.getSimpleName(), expected,
                        floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128), typeOfN));
            } else if (BigDecimal.class.equals(type)) {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toPlainString();
                Object actual = floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128),
                        BigDecimal.class).toPlainString();
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            } else {
                expected = INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128).toBigInteger();
                Object actual = floor((Object) INFINITY_DOUBLE.pow(10, MathContext.DECIMAL128),
                        BigInteger.class);
                assertEquals("Huge: " + type.getSimpleName(), expected, actual);
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
        }
    }
}

From source file:net.tradelib.misc.StrategyText.java

static private String formatDouble(double dd, int minPrecision, int maxPrecision) {
    BigDecimal bd = new BigDecimal(dd, MathContext.DECIMAL128);
    bd = bd.setScale(maxPrecision, RoundingMode.HALF_UP);
    return formatBigDecimal(bd);
}