Example usage for java.math BigDecimal longValueExact

List of usage examples for java.math BigDecimal longValueExact

Introduction

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

Prototype

public long longValueExact() 

Source Link

Document

Converts this BigDecimal to a long , checking for lost information.

Usage

From source file:Main.java

public static void main(String[] args) {

    BigDecimal bg1 = new BigDecimal("-999999");
    BigDecimal bg2 = new BigDecimal("3.3E+10");

    // assign the long value of bg1 and bg2 to l1,l2 respectively
    long l1 = bg1.longValueExact();
    long l2 = bg2.longValueExact();

    // print l1,l2 values
    System.out.println(l1);/*  w  w w  .j a  v a 2s  .  co m*/
    System.out.println(l2);
}

From source file:org.nuxeo.ecm.platform.el.FieldAdapterManager.java

/**
 * @since 7.1//w w  w .ja va2s  .c  om
 */
private static Long getBigDecimalAsLong(BigDecimal value) {
    return value.longValueExact();
}

From source file:org.coursera.courier.grammar.ParseUtils.java

public static Number toNumber(String string) {
    BigDecimal value = new BigDecimal(string);
    try {//from   w  ww.  j  av  a2s  .  c  o  m
        long l = value.longValueExact();
        int i = (int) l;
        if ((long) i == l) {
            return i;
        } else {
            return l;
        }
    } catch (ArithmeticException e) {
        double d = value.doubleValue();
        if (BigDecimal.valueOf(d).equals(value)) {
            float f = (float) d;
            if ((double) f == d) {
                return (float) d;
            } else {
                return d;
            }
        } else {
            return null;
        }
    }
}

From source file:org.eel.kitchen.jsonschema.GsonProvider.java

private static JsonNode toNumberNode(final BigDecimal decimal) {
    try {/* ww  w.  j ava  2  s .c om*/
        return factory.numberNode(decimal.intValueExact());
    } catch (ArithmeticException ignored) {
        try {
            return factory.numberNode(decimal.longValueExact());
        } catch (ArithmeticException ignoredAgain) {
            return decimal.scale() == 0 ? factory.numberNode(decimal.toBigInteger())
                    : factory.numberNode(decimal);
        }
    }
}

From source file:com.antsdb.saltedfish.sql.mysql.ExprGenerator.java

public static Operator genLiteralValue(GeneratorContext ctx, Planner planner, Literal_valueContext rule) {
    if (rule.literal_value_binary() != null) {
        return new BytesValue(getBytes(rule.literal_value_binary()));
    } else if (rule.literal_interval() != null) {
        return parseInterval(ctx, planner, rule.literal_interval());
    }//from w ww .j  a va2 s . com
    TerminalNode token = (TerminalNode) rule.getChild(0);
    switch (token.getSymbol().getType()) {
    case MysqlParser.NUMERIC_LITERAL: {
        BigDecimal bd = new BigDecimal(rule.getText());
        try {
            return new LongValue(bd.longValueExact());
        } catch (Exception ignored) {
        }
        return new NumericValue(new BigDecimal(rule.getText()));
    }
    case MysqlParser.STRING_LITERAL:
    case MysqlParser.DOUBLE_QUOTED_LITERAL:
        String value = Utils.getQuotedLiteralValue(rule);
        return new StringLiteral(value);
    case MysqlParser.K_NULL:
        return new NullValue();
    case MysqlParser.K_CURRENT_DATE:
        return new SysDate();
    case MysqlParser.K_CURRENT_TIME:
        return new CurrentTime();
    case MysqlParser.K_CURRENT_TIMESTAMP:
        return new CurrentTimestamp();
    case MysqlParser.K_TRUE:
        return new LongValue(1);
    case MysqlParser.K_FALSE:
        return new LongValue(0);
    case MysqlParser.BLOB_LITERAL:
        String text = rule.BLOB_LITERAL().getText();
        return new BytesValue(mysqlXBinaryToBytes(text));
    case MysqlParser.HEX_LITERAL:
        String hextxt = rule.HEX_LITERAL().getText();
        hextxt = hextxt.substring(2, hextxt.length());
        if (hextxt.length() == 0) {
            return new BytesValue(new byte[0]);
        }
        return new BytesValue(BytesUtil.hexToBytes(hextxt));
    default:
        throw new NotImplementedException();
    }
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkJMSProducerWrapper.java

private void runProducers(long rate, long duration) {

    BigDecimal bd = new BigDecimal(1000000).divide(new BigDecimal(rate), BigDecimal.ROUND_HALF_DOWN);
    long delayInMicroSeconds;
    try {/*from   ww  w . jav  a  2s  .  c o  m*/
        delayInMicroSeconds = bd.longValueExact();
    } catch (ArithmeticException e) {
        delayInMicroSeconds = bd.longValue();
        log().warn("Publish rate cannot be expressed as a precise microsecond value, rounding to nearest value "
                + "[actualDelay: " + delayInMicroSeconds + "]");
    }

    int producersNeeded = (int) (rate / getPartConfig().getMaxConsumerRatePerThread());
    if (producersNeeded == 0) {
        producersNeeded++;
    }

    log.debug("Running " + producersNeeded + " producers for " + duration + "s");
    producers = new ArrayList<BenchmarkProducer>(producersNeeded);
    sendingDelay = delayInMicroSeconds * producersNeeded;
    executor = new ScheduledThreadPoolExecutor(producersNeeded);

    for (int i = 0; i < producersNeeded; i++) {
        try {
            BenchmarkProducer producer = new BenchmarkProducer(this);
            producer.start();
            producer.setMessageCounter(getProbe());
            producers.add(producer);
        } catch (Exception e) {
            throw new BenchmarkConfigurationException("Unable to create BenchmarkProducer instance", e);
        }
    }
    for (BenchmarkProducer producer : producers) {
        // TODO should really hold onto these and monitor for failures until the
        // executor is shutdown
        executor.scheduleAtFixedRate(new MessageSender(producer), 0, sendingDelay, sendingDelayUnit);
    }

    final CountDownLatch latch = new CountDownLatch(1);

    new ScheduledThreadPoolExecutor(1).schedule(new Runnable() {
        public void run() {
            try {
                log.debug("Shutting down producers.");
                executor.shutdown();
                for (BenchmarkProducer producer : producers) {
                    try {
                        producer.release();
                    } catch (Exception e) {
                        log().error("Error releasing producer.");
                    }
                }
                latch.countDown();
            } catch (Exception e) {
            }
        }
    }, duration, TimeUnit.SECONDS);

    try {
        latch.await();
    } catch (InterruptedException ie) {
        log().warn("Producer run has been interrupted ...");
    }
}

From source file:org.kjots.json.content.io.simple.SimpleJsonReader.java

/**
 * Create the content handler./*from w ww. j  a v  a2s  . c o m*/
 *
 * @return The content handler.
 */
private ContentHandler createContentHandler() {
    return new ContentHandler() {
        @Override
        public void startJSON() {
            SimpleJsonReader.this.jsonContentHandler.startJson();
        }

        @Override
        public void endJSON() {
            SimpleJsonReader.this.jsonContentHandler.endJson();
        }

        @Override
        public boolean startObject() {
            SimpleJsonReader.this.jsonContentHandler.startObject();

            return true;
        }

        @Override
        public boolean endObject() {
            SimpleJsonReader.this.jsonContentHandler.endObject();

            return true;
        }

        @Override
        public boolean startObjectEntry(String key) {
            SimpleJsonReader.this.jsonContentHandler.memberName(key);

            return true;
        }

        @Override
        public boolean endObjectEntry() {
            return true;
        }

        @Override
        public boolean startArray() {
            SimpleJsonReader.this.jsonContentHandler.startArray();

            return true;
        }

        @Override
        public boolean endArray() {
            SimpleJsonReader.this.jsonContentHandler.endArray();

            return true;
        }

        @Override
        public boolean primitive(Object value) {
            if (value instanceof BigDecimal) {
                BigDecimal numericValue = (BigDecimal) value;

                // Attempt to coerce the value into an integer
                try {
                    value = Integer.valueOf(numericValue.intValueExact());
                } catch (ArithmeticException ae1) {
                    // Attempt to coerce the value into a long
                    try {
                        value = Long.valueOf(numericValue.longValueExact());
                    } catch (ArithmeticException ae2) {
                        // Attempt to coerce the value into a BigInteger
                        try {
                            value = numericValue.toBigIntegerExact();
                        } catch (ArithmeticException ae3) {
                            // Ignore this exception - value will remain a BigDecimal
                        }
                    }
                }
            }

            SimpleJsonReader.this.jsonContentHandler.primitive(value);

            return true;
        }
    };
}

From source file:org.ojai.json.impl.JsonStreamDocumentReader.java

@Override
public long getDecimalValueAsLong() {
    BigDecimal decimal = getDecimal();
    if (decimal != null) {
        return decimal.longValueExact();
    }//from   w ww . j  a  va 2 s . c o  m
    return 0;
}

From source file:org.raml.jaxrs.codegen.core.AbstractGenerator.java

private void addMinMaxConstraint(final AbstractParam parameter, final String name,
        final Class<? extends Annotation> clazz, final BigDecimal value, final JVar argumentVariable) {
    try {/*from w  w w .j a va2 s .  c  o m*/
        final long boundary = value.longValueExact();
        argumentVariable.annotate(clazz).param(DEFAULT_ANNOTATION_PARAMETER, boundary);
    } catch (final ArithmeticException ae) {
        LOGGER.info("Non integer " + name + " constraint ignored for parameter: "
                + ToStringBuilder.reflectionToString(parameter, SHORT_PREFIX_STYLE));
    }
}

From source file:org.seasar.dbflute.logic.replaceschema.loaddata.impl.DfAbsractDataWriter.java

protected boolean processNumber(String tableName, String columnName, String value, Connection conn,
        PreparedStatement ps, int bindCount, Map<String, DfColumnMeta> columnInfoMap) throws SQLException {
    if (value == null) {
        return false; // basically no way
    }//from  ww w.  ja v a 2  s. com
    final DfColumnMeta columnInfo = columnInfoMap.get(columnName);
    if (columnInfo != null) {
        final Class<?> columnType = getBindType(tableName, columnInfo);
        if (columnType != null) {
            if (!Number.class.isAssignableFrom(columnType)) {
                return false;
            }
            bindNotNullValueByColumnType(tableName, columnName, conn, ps, bindCount, value, columnType);
            return true;
        }
    }
    // if meta data is not found (basically no way)
    value = filterBigDecimalValue(value);
    if (!isBigDecimalValue(value)) {
        return false;
    }
    final BigDecimal bigDecimalValue = getBigDecimalValue(columnName, value);
    try {
        final long longValue = bigDecimalValue.longValueExact();
        ps.setLong(bindCount, longValue);
        return true;
    } catch (ArithmeticException e) {
        ps.setBigDecimal(bindCount, bigDecimalValue);
        return true;
    }
}