List of usage examples for java.lang Number floatValue
public abstract float floatValue();
From source file:io.fabric8.jolokia.support.JolokiaHelpers.java
public static Object convertJolokiaToJavaType(Class<?> clazz, Object value) throws IOException { if (clazz.isArray()) { if (value instanceof JSONArray) { JSONArray jsonArray = (JSONArray) value; Object[] javaArray = (Object[]) Array.newInstance(clazz.getComponentType(), jsonArray.size()); int idx = 0; for (Object element : jsonArray) { Array.set(javaArray, idx++, convertJolokiaToJavaType(clazz.getComponentType(), element)); }/*from www. ja va 2 s . c om*/ return javaArray; } else { return null; } } else if (String.class.equals(clazz)) { return (value != null) ? value.toString() : null; } else if (clazz.equals(Byte.class) || clazz.equals(byte.class)) { Number number = asNumber(value); return number != null ? number.byteValue() : null; } else if (clazz.equals(Short.class) || clazz.equals(short.class)) { Number number = asNumber(value); return number != null ? number.shortValue() : null; } else if (clazz.equals(Integer.class) || clazz.equals(int.class)) { Number number = asNumber(value); return number != null ? number.intValue() : null; } else if (clazz.equals(Long.class) || clazz.equals(long.class)) { Number number = asNumber(value); return number != null ? number.longValue() : null; } else if (clazz.equals(Float.class) || clazz.equals(float.class)) { Number number = asNumber(value); return number != null ? number.floatValue() : null; } else if (clazz.equals(Double.class) || clazz.equals(double.class)) { Number number = asNumber(value); return number != null ? number.doubleValue() : null; } else if (value instanceof JSONObject) { JSONObject jsonObject = (JSONObject) value; if (!JSONObject.class.isAssignableFrom(clazz)) { String json = jsonObject.toJSONString(); return getObjectMapper().readerFor(clazz).readValue(json); } } return value; }
From source file:com.helpinput.core.Utils.java
public static boolean equals(final Object sourceV, final Object filterV) { if (sourceV == null) { return filterV == null; }//from ww w.j a va 2 s .c om if (filterV == null) return false; if ((sourceV instanceof Number)) { if (!(filterV instanceof Number)) return false; Number v1 = (Number) sourceV; Number v2 = (Number) filterV; return v1.floatValue() == v2.floatValue(); } return sourceV.equals(filterV); }
From source file:org.red5.server.service.ConversionUtils.java
/** * Convert number to primitive wrapper like Boolean or Float * @param num Number to conver * @param wrapper Primitive wrapper type * @return Converted object *///from ww w .j av a2s . co m public static Object convertNumberToWrapper(Number num, Class<?> wrapper) { //XXX Paul: Using valueOf will reduce object creation if (wrapper.equals(String.class)) { return num.toString(); } else if (wrapper.equals(Boolean.class)) { return Boolean.valueOf(num.intValue() == 1); } else if (wrapper.equals(Double.class)) { return Double.valueOf(num.doubleValue()); } else if (wrapper.equals(Long.class)) { return Long.valueOf(num.longValue()); } else if (wrapper.equals(Float.class)) { return Float.valueOf(num.floatValue()); } else if (wrapper.equals(Integer.class)) { return Integer.valueOf(num.intValue()); } else if (wrapper.equals(Short.class)) { return Short.valueOf(num.shortValue()); } else if (wrapper.equals(Byte.class)) { return Byte.valueOf(num.byteValue()); } throw new ConversionException("Unable to convert number to: " + wrapper); }
From source file:Main.java
/** * convert value to given type.//from w ww. j a v a2s .c o m * null safe. * * @param value value for convert * @param type will converted type * @return value while converted */ public static Object convertCompatibleType(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return Short.valueOf(string); } else if (type == Integer.class || type == int.class) { return Integer.valueOf(string); } else if (type == Long.class || type == long.class) { return Long.valueOf(string); } else if (type == Double.class || type == double.class) { return Double.valueOf(string); } else if (type == Float.class || type == float.class) { return Float.valueOf(string); } else if (type == Byte.class || type == byte.class) { return Byte.valueOf(string); } else if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { return forName((String) value); } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { e.printStackTrace(); } } else if (type == List.class) { return new ArrayList<>(collection); } else if (type == Set.class) { return new HashSet<>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<>(); } } else if (type == Set.class) { collection = new HashSet<>(); } else { collection = new ArrayList<>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; }
From source file:nl.strohalm.cyclos.utils.conversion.CoercionHelper.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Object convert(Class toType, Object value) { if ("".equals(value)) { value = null;/*w ww .j a v a 2s .c o m*/ } // If we do not want a collection, but the value is one, use the first value if (value != null && !(Collection.class.isAssignableFrom(toType) || toType.isArray()) && (value.getClass().isArray() || value instanceof Collection)) { final Iterator it = IteratorUtils.getIterator(value); if (!it.hasNext()) { value = null; } else { value = it.next(); } } // Check for null values if (value == null) { if (toType.isPrimitive()) { // On primitives, use the default value if (toType == Boolean.TYPE) { value = Boolean.FALSE; } else if (toType == Character.TYPE) { value = '\0'; } else { value = 0; } } else { // For objects, return null return null; } } // Check if the value is already of the expected type if (toType.isInstance(value)) { return value; } // If the class is primitive, use the wrapper, so we have an easier work of testing instances if (toType.isPrimitive()) { toType = ClassUtils.primitiveToWrapper(toType); } // Convert to well-known types if (String.class.isAssignableFrom(toType)) { if (value instanceof Entity) { final Long entityId = ((Entity) value).getId(); return entityId == null ? null : entityId.toString(); } return value.toString(); } else if (Number.class.isAssignableFrom(toType)) { if (!(value instanceof Number)) { if (value instanceof String) { value = new BigDecimal((String) value); } else if (value instanceof Date) { value = ((Date) value).getTime(); } else if (value instanceof Calendar) { value = ((Calendar) value).getTimeInMillis(); } else if (value instanceof Entity) { value = ((Entity) value).getId(); if (value == null) { return null; } } else { throw new ConversionException("Invalid number: " + value); } } final Number number = (Number) value; if (Byte.class.isAssignableFrom(toType)) { return number.byteValue(); } else if (Short.class.isAssignableFrom(toType)) { return number.shortValue(); } else if (Integer.class.isAssignableFrom(toType)) { return number.intValue(); } else if (Long.class.isAssignableFrom(toType)) { return number.longValue(); } else if (Float.class.isAssignableFrom(toType)) { return number.floatValue(); } else if (Double.class.isAssignableFrom(toType)) { return number.doubleValue(); } else if (BigInteger.class.isAssignableFrom(toType)) { return new BigInteger(number.toString()); } else if (BigDecimal.class.isAssignableFrom(toType)) { return new BigDecimal(number.toString()); } } else if (Boolean.class.isAssignableFrom(toType)) { if (value instanceof Number) { return ((Number) value).intValue() != 0; } else if ("on".equalsIgnoreCase(value.toString())) { return true; } else { return Boolean.parseBoolean(value.toString()); } } else if (Character.class.isAssignableFrom(toType)) { final String str = value.toString(); return (str.length() == 0) ? null : str.charAt(0); } else if (Calendar.class.isAssignableFrom(toType)) { if (value instanceof Date) { final Calendar cal = new GregorianCalendar(); cal.setTime((Date) value); return cal; } } else if (Date.class.isAssignableFrom(toType)) { if (value instanceof Calendar) { final long millis = ((Calendar) value).getTimeInMillis(); try { return ConstructorUtils.invokeConstructor(toType, millis); } catch (final Exception e) { throw new IllegalStateException(e); } } } else if (Enum.class.isAssignableFrom(toType)) { Object ret; try { ret = Enum.valueOf(toType, value.toString()); } catch (final Exception e) { ret = null; } if (ret == null) { Object[] possible; try { possible = (Object[]) toType.getMethod("values").invoke(null); } catch (final Exception e) { throw new IllegalStateException( "Couldn't invoke the 'values' method for enum " + toType.getName()); } if (StringValuedEnum.class.isAssignableFrom(toType)) { final String test = coerce(String.class, value); for (final Object item : possible) { if (((StringValuedEnum) item).getValue().equals(test)) { ret = item; break; } } } else if (IntValuedEnum.class.isAssignableFrom(toType)) { final int test = coerce(Integer.TYPE, value); for (final Object item : possible) { if (((IntValuedEnum) item).getValue() == test) { ret = item; break; } } } else { throw new ConversionException("Invalid enum: " + value); } } return ret; } else if (Entity.class.isAssignableFrom(toType)) { final Long id = coerce(Long.class, value); return EntityHelper.reference(toType, id); } else if (Locale.class.isAssignableFrom(toType)) { return LocaleConverter.instance().valueOf(value.toString()); } else if (Collection.class.isAssignableFrom(toType)) { final Collection collection = (Collection) ClassHelper.instantiate(toType); final Iterator iterator = IteratorUtils.getIterator(value); while (iterator.hasNext()) { collection.add(iterator.next()); } return collection; } else if (toType.isArray()) { final Collection collection = coerceCollection(toType.getComponentType(), value); final Object[] array = (Object[]) Array.newInstance(toType.getComponentType(), collection.size()); return collection.toArray(array); } // We don't know how to convert the value throw new ConversionException("Cannot coerce value to: " + toType.getName()); }
From source file:voldemort.VoldemortClientShell.java
@SuppressWarnings("unchecked") protected static Object tightenNumericTypes(Object o) { if (o == null) { return null; } else if (o instanceof List) { List l = (List) o; for (int i = 0; i < l.size(); i++) l.set(i, tightenNumericTypes(l.get(i))); return l; } else if (o instanceof Map) { Map m = (Map) o;//from w w w . j a va 2 s .co m for (Map.Entry entry : (Set<Map.Entry>) m.entrySet()) m.put(entry.getKey(), tightenNumericTypes(entry.getValue())); return m; } else if (o instanceof Number) { Number n = (Number) o; if (o instanceof Integer) { if (n.intValue() < Byte.MAX_VALUE) return n.byteValue(); else if (n.intValue() < Short.MAX_VALUE) return n.shortValue(); else return n; } else if (o instanceof Double) { if (n.doubleValue() < Float.MAX_VALUE) return n.floatValue(); else return n; } else { throw new RuntimeException("Unsupported numeric type: " + o.getClass()); } } else { return o; } }
From source file:de.cebitec.readXplorer.util.GeneralUtils.java
/** * Converts a given number into a number of the given classType. If this is * not possible, it throws a ClassCastException * @param <T> one of the classes derived from Number * @param classType the type to convert the number into * @param number the number to convert/*from w w w. j a v a2s . c om*/ * @return The converted number */ public static <T extends Number> T convertNumber(Class<T> classType, Number number) throws ClassCastException { T convertedValue = null; if (classType.equals(Integer.class)) { convertedValue = classType.cast(number.intValue()); } else if (classType.equals(Double.class)) { convertedValue = classType.cast(number.doubleValue()); } else if (classType.equals(Long.class)) { convertedValue = classType.cast(number.longValue()); } else if (classType.equals(Float.class)) { convertedValue = classType.cast(number.floatValue()); } else if (classType.equals(Short.class)) { convertedValue = classType.cast(number.shortValue()); } else if (classType.equals(Byte.class)) { convertedValue = classType.cast(number.byteValue()); } if (convertedValue == null) { throw new ClassCastException("Cannot cast the given number into the given format."); } return convertedValue; }
From source file:demo.config.PropertyConverter.java
/** * Convert the specified object into a Float. * /* w w w .j av a 2 s .com*/ * @param value * the value to convert * @return the converted value * @throws ConversionException * thrown if the value cannot be converted to a Float */ public static Float toFloat(Object value) throws ConversionException { Number n = toNumber(value, Float.class); if (n instanceof Float) { return (Float) n; } else { return new Float(n.floatValue()); } }
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 {/*from w w w .j a v a 2 s . c o m*/ 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:org.squale.squalecommon.enterpriselayer.facade.rule.AuditComputing.java
/** * Calcul de la note sur un projet Le calcul de la note sur un projet se fait directement au moyen de la formule * associe/*from w w w . j ava 2 s .co m*/ * * @param pSession session * @param pProject projet * @param pAudit audit * @param pInterpreter interprte * @param pPractice pratique * @param pPracticeResult rsultat * @throws FormulaException si erreur * @throws JrafDaoException si erreur */ private static void computeProjectPracticeMark(ISession pSession, ProjectBO pProject, AuditBO pAudit, FormulaInterpreter pInterpreter, PracticeRuleBO pPractice, PracticeResultBO pPracticeResult) throws JrafDaoException, FormulaException { // Rcupration des types de mesure traits par la formule AbstractFormulaBO formula = pPractice.getFormula(); String[] measureKinds = new String[formula.getMeasureKinds().size()]; formula.getMeasureKinds().toArray(measureKinds); MeasureBO[] measures = new MeasureBO[formula.getMeasureKinds().size()]; Long projectId = new Long(pProject.getId()); // Rcupration de chaque mesure boolean measuresNotNull = true; Long auditId = new Long(pAudit.getId()); for (int i = 0; i < measureKinds.length; i++) { MeasureBO measure = (MeasureBO) MeasureDAOImpl.getInstance().load(pSession, projectId, auditId, Mapping.getMeasureClass(measureKinds[i] + "." + formula.getComponentLevel())); measures[i] = measure; // Une mesure peut tre absente, ce qui serait li un problme de cration des mesures // dans la phase qui prcde le calcul des notes if (measure == null) { measuresNotNull = false; // On indique le type de mesure qui n'est pas trouv ainsi que le composant concern LOG.warn(RuleMessages.getString("missingmeasure", new Object[] { measureKinds[i], projectId, auditId })); } } // On calcul la note seulement si toutes les mesures requises sont bien prsentes if (measuresNotNull) { // Calcul de la note // L'exception dans le calcul est remonte telle quelle Number value = pInterpreter.evaluate(pPractice.getFormula(), measures); // On place une note -1 si la formule n'a pu tre calcule if (value != null) { pPracticeResult.setMeanMark(value.floatValue()); } } }