List of usage examples for java.lang Number doubleValue
public abstract double doubleValue();
From source file:NumberUtils.java
/** * Compares the first number to the second one numerically and * returns an integer depending on the comparison result: * a negative value if the first number is the smaller one, * a zero value if they are equal, and/*from ww w . j a v a2 s.co m*/ * a positive value if the first number is the larger one. * * The main strategy goes like follows: * 1. If one of the arguments is <code>null</code> or 'not a number', * throw an exception. * 2. If both values are 'long compatible', compare their <code>longValue()</code> * using the usual comparison operators for primitive types (<, ==, >). * 3. If both values are 'double compatible', compare their <code>doubleValue()</code> * using the usual comparison operators for primitive types (<, ==, >). * 4. If one of the values is infinite (and the other is finite), * determine the result depending on the sign of the infinite value. * 5. Otherwise convert both values to <code>java.math.BigDecimal</code> and * return the result of the <code>BigDecimal.compareTo(BigDecimal)</code> method. * * As a consequence, the method is not suitable to implement a * <code>java.util.Comparator</code> for numbers. To achieve this, * one had to accept 'not a number' arguments and place them somewhere * in the row of numbers (probably at the upper end, i.e. larger than * positive infinity, as <code>Double.compare(double, double)</code> * does it). * So the behavior of this method is like that of the comparison * operator for primitive types and not like that of the related * <code>compareTo(...)</code> methods. Besides the handling of * 'not a number' values this makes a difference, when comparing * the float or double values <code>-0.0</code> and <code>0.0</code>: * again, like the operators, we consider them as equal (whereas * according to <code>Double.compareTo(...)</code> <code>-0.0</code> * is less than <code>0.0</code>). * * @param first * @param second * @return int * @throws ArithmeticException One or both of the given numbers is <code>null</code> or 'not a number'. */ public static int compare(Number first, Number second) throws ArithmeticException { if (first == null || second == null || isNaN(first) || isNaN(second)) throw new ArithmeticException("Arguments must not be null or NaN."); int result = -2; if (isLongCompatible(first) && isLongCompatible(second)) { long v1 = first.longValue(), v2 = second.longValue(); result = v1 < v2 ? -1 : v1 == v2 ? 0 : v1 > v2 ? 1 : 2; } else if (isDoubleCompatible(first) && isDoubleCompatible(second)) { double v1 = first.doubleValue(), v2 = second.doubleValue(); result = v1 < v2 ? -1 : v1 == v2 ? 0 : v1 > v2 ? 1 : 2; } if (result == 2) // should not happen throw new ArithmeticException("Arguments " + first + " and " + second + " are not comparable."); if (result > -2) return result; if (isInfinite(first)) // => second is finite return first.doubleValue() == Double.NEGATIVE_INFINITY ? -1 : 1; if (isInfinite(second)) // => first is finite return second.doubleValue() == Double.POSITIVE_INFINITY ? -1 : 1; return toBigDecimal(first).compareTo(toBigDecimal(second)); }
From source file:com.amazonaws.hal.client.ConversionUtil.java
private static Object convertFromNumber(Class<?> clazz, Number value) { if (String.class.isAssignableFrom(clazz)) { return value.toString(); } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) { return value.intValue(); } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) { return value.longValue(); } else if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) { return value.shortValue(); } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) { return value.doubleValue(); } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) { return value.floatValue(); } else if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) { return Boolean.valueOf(value.toString()); } else if (char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) { if (value.longValue() <= 255) { return (char) value.longValue(); } else {// w w w . ja v a2s . c om throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName()); } } else if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)) { return value.byteValue(); } else if (BigDecimal.class.isAssignableFrom(clazz)) { return new BigDecimal(value.toString()); } else if (BigInteger.class.isAssignableFrom(clazz)) { // Necessary because BigInteger(long) is a private method and we need to convert the Number to a long to // prevent the constructor from throwing a NumberFormatException Example: BigInteger(1.2) return new BigInteger(String.valueOf(value.longValue())); } else if (Date.class.isAssignableFrom(clazz)) { return new Date(value.longValue()); } else if (clazz.isEnum()) { try { //noinspection unchecked return Enum.valueOf((Class<Enum>) clazz, value.toString()); } catch (IllegalArgumentException e) { log.error(String.format( "'%s' is not a recognized enum value for %s. Returning default of %s instead.", value, clazz.getName(), clazz.getEnumConstants()[0])); return clazz.getEnumConstants()[0]; } } else { throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName()); } }
From source file:com.opendoorlogistics.core.tables.io.PoiIO.java
private static SaveElementResult saveElementToCell(ODLTableReadOnly table, int row, int col, Cell cell) { boolean oversized = false; switch (table.getColumnType(col)) { case LONG:/*from w w w .ja va 2s . c o m*/ case DOUBLE: Number dVal = (Number) table.getValueAt(row, col); if (dVal != null) { cell.setCellValue(dVal.doubleValue()); cell.setCellType(Cell.CELL_TYPE_NUMERIC); } else { cell.setCellValue((String) null); cell.setCellType(Cell.CELL_TYPE_BLANK); } break; default: String sval = TableUtils.getValueAsString(table, row, col); if (sval != null) { if (sval.length() >= MAX_CHAR_COUNT_IN_EXCEL_CELL) { oversized = true; } cell.setCellValue(sval.toString()); } else { cell.setCellValue((String) null); } cell.setCellType(Cell.CELL_TYPE_STRING); break; } return oversized ? SaveElementResult.OVERSIZED : SaveElementResult.OK; }
From source file:NumberUtils.java
/** * Answers the signum function of the given number * (i.e., <code>-1</code> if it is negative, <code>0</code> * if it is zero and <code>1</code> if it is positive). * * @param number/*from ww w .j a v a 2s. c o m*/ * @return int * @throws ArithmeticException The given number is <code>null</code> or 'not a number'. */ public static int signum(Number number) throws ArithmeticException { if (number == null || isNaN(number)) throw new ArithmeticException("Argument must not be null or NaN."); if (isLongCompatible(number)) { long value = number.longValue(); return value < 0 ? -1 : value == 0 ? 0 : 1; } else if (number instanceof BigInteger) return ((BigInteger) number).signum(); else if (number instanceof BigDecimal) return ((BigDecimal) number).signum(); else { // => isDoubleCompatible(number) or unknown Number type double value = number.doubleValue(); return value < 0 ? -1 : value == 0 ? 0 : 1; } }
From source file:dk.nodes.webservice.parser.NJSONObject.java
/** * Encodes the number as a JSON string.//from w w w . j av a 2 s .c o m * * @param number a finite value. May not be {@link Double#isNaN() NaNs} or * {@link Double#isInfinite() infinities}. */ public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Number must be non-null"); } double doubleValue = number.doubleValue(); NJSON.checkDouble(doubleValue); // the original returns "-0" instead of "-0.0" for negative zero if (number.equals(NEGATIVE_ZERO)) { return "-0"; } long longValue = number.longValue(); if (doubleValue == (double) longValue) { return Long.toString(longValue); } return number.toString(); }
From source file:net.sf.jasperreports.functions.standard.MathFunctions.java
/** * Returns the absolute value of a number. *///from www .j ava 2s .c o m @Function("ABS") @FunctionParameters({ @FunctionParameter("number") }) public static Number ABS(Number number) { if (number == null) { logNullArgument(); return null; } else { if (number instanceof Integer) { return Math.abs((Integer) number); } else if (number instanceof Double) { return Math.abs((Double) number); } else if (number instanceof Float) { return Math.abs((Float) number); } else if (number instanceof Long) { return Math.abs((Long) number); } else { // fall-back return Math.abs(number.doubleValue()); } } }
From source file:it.govpay.web.utils.Utils.java
public static String fileSizeConverter(Number bytes) { MessageFormat mf = new MessageFormat("{0,number,#.##}"); Double len = null;/*from w w w.java2 s . co m*/ String res = ""; // il valore e' in byte len = bytes.doubleValue(); long d = Math.round(len / 1024); //Originale e funzionante :) // if (d <= 1) { // // byte // Object[] objs = { len }; // res = mf.format(objs); // res += " B"; // } else if (d > 1 && d < 1000) { // // kilo byte // Object[] objs = { len / 1024 }; // res = mf.format(objs); // res += " KB"; // } else { // // mega byte // Object[] objs = { len / 1048576 }; // res = mf.format(objs); // res += " MB"; // } if (d <= 1) { // byte Object[] objs = { len }; res = mf.format(objs); res += " B"; } else if (d > 1 && d < 1000) { // kilo byte Object[] objs = { len / 1024 }; res = mf.format(objs); res += " KB"; } else if (d >= 1000 && d < 1000000) { // mega byte Object[] objs = { len / 1048576 }; res = mf.format(objs); res += " MB"; } else { // giga byte Object[] objs = { len / 1073741824 }; res = mf.format(objs); res += " GB"; } return res; }
From source file:NumberUtils.java
/** * Converts the given number to a <code>java.math.BigDecimal</code>. * * @param number/*www . j a v a 2s . c o m*/ * @return java.math.BigDecimal * @throws IllegalArgumentException The given number is 'not a number' or infinite. */ public static BigDecimal toBigDecimal(Number number) throws IllegalArgumentException { if (number == null || number instanceof BigDecimal) return (BigDecimal) number; if (number instanceof BigInteger) return new BigDecimal((BigInteger) number); if (isDoubleCompatible(number)) { if (isNaN(number) || isInfinite(number)) throw new IllegalArgumentException("Argument must not be NaN or infinite."); return new BigDecimal(number.toString()); } if (isLongCompatible(number)) return BigDecimal.valueOf(number.longValue()); // => unknown Number type return new BigDecimal(String.valueOf(number.doubleValue())); }
From source file:gov.nasa.jpf.constraints.solvers.cw.CWSolver.java
public static Number evaluateAndSubtractSides(NumericBooleanExpression constraint, Valuation valuation) { Object leftVal = constraint.getLeft().evaluate(valuation); Object rightVal = constraint.getRight().evaluate(valuation); if (!(leftVal instanceof Number && rightVal instanceof Number) && !(leftVal instanceof Boolean && rightVal instanceof Boolean)) throw new IllegalStateException( "left and right hand side must evaluate to a number or boolean; not Ltype: " + leftVal.getClass().getName() + " RType: " + rightVal.getClass().getName()); Number l; //DELETE? if (leftVal instanceof Boolean) { Boolean lv = (Boolean) leftVal; l = (lv) ? 1.0 : 0.0;/*ww w.java2 s .c o m*/ } else l = (Number) leftVal; boolean leftIsNegative = l.doubleValue() < 0; Number r; //DELETE? if (rightVal instanceof Boolean) { Boolean rv = (Boolean) rightVal; r = (rv) ? 1.0 : 0.0; } else r = (Number) rightVal; boolean rightIsNegative = r.doubleValue() < 0; //TODO: not sure if this is correct.. double check with original implementation Number result = l.doubleValue() - r.doubleValue(); if (leftIsNegative == rightIsNegative) { // Can neither overflow nor underflow return result; } boolean resultIsNegative = result.doubleValue() < 0; boolean underflowOccurred = leftIsNegative && !resultIsNegative; boolean overflowOccurred = rightIsNegative && resultIsNegative; if (!underflowOccurred && !overflowOccurred) { return result; } if (result instanceof Integer) { return (underflowOccurred ? Integer.MIN_VALUE : Integer.MAX_VALUE); } else if (result instanceof Double) { return (underflowOccurred ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); } else { throw new AssertionError("Result has unknown number type: " + result); } }
From source file:com.jkoolcloud.tnt4j.streams.utils.NumericFormatter.java
/** * Formats the specified object using the defined pattern, or using the default numeric formatting if no pattern was * defined./*www . j a va 2 s . c o m*/ * * @param formatter * formatter object to apply to value * @param radix * the radix to use while parsing numeric strings * @param value * value to convert * @param scale * value to multiply the formatted value by * * @return formatted value of field in required internal data type * * @throws ParseException * if an error parsing the specified value based on the field definition (e.g. does not match defined * pattern, etc.) */ private static Number parse(DecimalFormat formatter, int radix, Object value, Number scale) throws ParseException { if (value == null) { return null; } if (scale == null) { scale = 1.0; } try { Number numValue = null; if (formatter == null && value instanceof String) { String strValue = (String) value; if (strValue.startsWith("0x") || strValue.startsWith("0X")) { // NON-NLS numValue = Long.parseLong(strValue.substring(2), 16); } } if (numValue == null) { if (formatter != null) { numValue = formatter.parse(value.toString()); } else if (radix != 10) { numValue = Long.parseLong(value.toString(), radix); } else { numValue = value instanceof Number ? (Number) value : Double.valueOf(value.toString()); } } Number scaledValue = numValue.doubleValue() * scale.doubleValue(); return Utils.castNumber(scaledValue, numValue.getClass()); } catch (NumberFormatException nfe) { throw new ParseException(nfe.getLocalizedMessage(), 0); } }