Example usage for java.lang Float valueOf

List of usage examples for java.lang Float valueOf

Introduction

In this page you can find the example usage for java.lang Float valueOf.

Prototype

@HotSpotIntrinsicCandidate
public static Float valueOf(float f) 

Source Link

Document

Returns a Float instance representing the specified float value.

Usage

From source file:Main.java

/**
 * convert value to given type./*from   w w w. j ava  2  s . 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:Main.java

/**
 * parse a string to an Object of given data type. <br>
 * @param strValue the string value/* ww w.  ja v  a2s .c  o m*/
 * @param valueType the full java class name which could be <br>
 * java.util.Date   (default format is yyyy-MM-dd) <br>
 * java.sql.Date   (default format is yyyy-MM-dd) <br>
 * java.sql.Timestamp   (default format is yyyy-MM-dd HH:mm:ss) <br>
 * java.sql.Time   (default format is HH:mm:ss) <br>
 * java.lang.String   <br>
 * java.lang.Boolean   <br>
 * java.lang.Double   <br>
 * java.lang.Long   <br>
 * java.lang.Short   <br>
 * java.lang.Integer   <br>
 * java.lang.Byte   <br>
 * java.lang.Float   <br>
 * java.math.BigInteger   <br>
 * java.math.BigDecimal   <br>
 * 
 * @param format SimpleDateFormat allowed standard formats.
 * @return Object
 * @throws Exception
 */
public static Object parseStringToObject(String strValue, String valueType, String format) throws Exception {
    if ("java.util.Date".equals(valueType)) {
        // default format yyyy-MM-dd
        SimpleDateFormat fmt = new SimpleDateFormat(format != null ? format : "yyyy-MM-dd");
        return (fmt.parse(strValue));
    } else if ("java.sql.Date".equals(valueType)) {
        // default format yyyy-MM-dd
        SimpleDateFormat fmt = new SimpleDateFormat(format != null ? format : "yyyy-MM-dd");
        return (new java.sql.Date(fmt.parse(strValue).getTime()));
    } else if ("java.sql.Timestamp".equals(valueType)) {
        // default format yyyy-MM-dd HH:mm:ss
        SimpleDateFormat fmt = new SimpleDateFormat(format != null ? format : "yyyy-MM-dd HH:mm:ss");
        return (new java.sql.Timestamp(fmt.parse(strValue).getTime()));
    } else if ("java.sql.Time".equals(valueType)) {
        // default format HH:mm:ss
        SimpleDateFormat fmt = new SimpleDateFormat(format != null ? format : "HH:mm:ss");
        return (new java.sql.Time(fmt.parse(strValue).getTime()));
    } else if ("java.lang.Boolean".equals(valueType)) {
        return (Boolean.valueOf(strValue));
    } else if ("java.lang.Double".equals(valueType)) {
        return (Double.valueOf(strValue));
    } else if ("java.lang.Long".equals(valueType)) {
        return (Long.valueOf(strValue));
    } else if ("java.lang.Short".equals(valueType)) {
        return (Short.valueOf(strValue));
    } else if ("java.lang.Integer".equals(valueType)) {
        return (Integer.valueOf(strValue));
    } else if ("java.lang.Byte".equals(valueType)) {
        return (Byte.valueOf(strValue));
    } else if ("java.lang.Float".equals(valueType)) {
        return (Float.valueOf(strValue));
    } else if ("java.math.BigInteger".equals(valueType)) {
        return (new java.math.BigInteger(strValue));
    } else if ("java.math.BigDecimal".equals(valueType)) {
        return (new java.math.BigDecimal(strValue));
    } else {
        return (strValue);
    }
}

From source file:gov.nih.nci.caintegrator.common.CentralTendencyCalculatorTest.java

/**
 * Calculate central tendency with no variance.
 *//*from  ww  w  .ja va2  s  . c  om*/
@Test
public void calculateCentralTendencyValueNoVariance() {
    calculatorNoVariance.calculateCentralTendencyValue(values1);
    assertEquals(Float.valueOf(5), calculatorNoVariance.getCentralTendencyValue());

    values1 = ArrayUtils.add(values1, 8f);
    calculatorNoVariance.calculateCentralTendencyValue(values1);
    assertEquals(Float.valueOf("5.6"), calculatorNoVariance.getCentralTendencyValue());
    calculatorNoVariance = new CentralTendencyCalculator(CentralTendencyTypeEnum.MEDIAN);
    calculatorNoVariance.calculateCentralTendencyValue(values1);
    assertEquals(Float.valueOf("6"), calculatorNoVariance.getCentralTendencyValue());
}

From source file:NumberUtils.java

/**
 * Parse the given text into a number instance of the given target class,
 * using the corresponding default <code>decode</code> methods. Trims the
 * input <code>String</code> before attempting to parse the number. Supports
 * numbers in hex format (with leading 0x) and in octal format (with leading 0).
 * @param text the text to convert/*from w ww .j ava2  s  . co  m*/
 * @param targetClass the target class to parse into
 * @return the parsed number
 * @throws IllegalArgumentException if the target class is not supported
 * (i.e. not a standard Number subclass as included in the JDK)
 * @see java.lang.Byte#decode
 * @see java.lang.Short#decode
 * @see java.lang.Integer#decode
 * @see java.lang.Long#decode
 * @see #decodeBigInteger(String)
 * @see java.lang.Float#valueOf
 * @see java.lang.Double#valueOf
 * @see java.math.BigDecimal#BigDecimal(String)
 */
public static Number parseNumber(String text, Class<?> targetClass) {
    //   Assert.notNull(text, "Text must not be null");
    //Assert.notNull(targetClass, "Target class must not be null");

    String trimmed = text.trim();

    if (targetClass.equals(Byte.class)) {
        return Byte.decode(trimmed);
    } else if (targetClass.equals(Short.class)) {
        return Short.decode(trimmed);
    } else if (targetClass.equals(Integer.class)) {
        return Integer.decode(trimmed);
    } else if (targetClass.equals(Long.class)) {
        return Long.decode(trimmed);
    } else if (targetClass.equals(BigInteger.class)) {
        return decodeBigInteger(trimmed);
    } else if (targetClass.equals(Float.class)) {
        return Float.valueOf(trimmed);
    } else if (targetClass.equals(Double.class)) {
        return Double.valueOf(trimmed);
    } else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
        return new BigDecimal(trimmed);
    } else {
        throw new IllegalArgumentException(
                "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
    }
}

From source file:fr.zcraft.zbanque.utils.LocationUtils.java

/**
 * Converts a string location (format "x;y;z" or "x;y;z;pitch" or "x;y;z;pitch;yaw") to a
 * location object./* ww w .j a  va2s  .  c om*/
 *
 * @param world The world.
 * @param raw   The raw string.
 *
 * @return The location.
 * @throws IllegalArgumentException if the format is not valid.
 */
public static Location string2Location(World world, String raw) {
    String[] parts = raw.split(";");
    Validate.isTrue(parts.length >= 3, "The location must contains at least three coordinates");

    Location location = new Location(world, Double.valueOf(parts[0]), Double.valueOf(parts[1]),
            Double.valueOf(parts[2]));

    if (parts.length >= 4)
        location.setPitch(Float.valueOf(parts[3]));

    if (parts.length >= 5)
        location.setYaw(Float.valueOf(parts[4]));

    return location;
}

From source file:com.yahoo.egads.models.adm.AnomalyDetectionAbstractModel.java

protected Map<String, Float> parseMap(String s) {
    if (s == null) {
        return new HashMap<String, Float>();
    }/*from  w  ww. j a  v a  2s .co m*/
    String[] pairs = s.split(",");
    Map<String, Float> myMap = new HashMap<String, Float>();
    for (int i = 0; i < pairs.length; i++) {
        String pair = pairs[i];
        String[] keyValue = pair.split("#");
        myMap.put(keyValue[0], Float.valueOf(keyValue[1]));
    }
    return myMap;
}

From source file:com.adaptris.core.services.jdbc.FloatStatementParameter.java

Float toFloat(Object value) throws ServiceException {
    if (isBlank((String) value) && convertNull()) {
        return Float.valueOf(NumberUtils.toFloat((String) value));
    } else {/* w  w w .  j  a  va 2  s . c  o  m*/
        return Float.valueOf((String) value);
    }
}

From source file:com.sms.server.service.parser.NFOParser.java

public MediaElement parse(MediaElement mediaElement) {
    // Get XML file
    File nfoFile = getNFOFile(mediaElement.getParentPath());

    if (nfoFile != null) {
        LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME,
                "Parsing NFO file " + nfoFile.getPath(), null);

        try {/*from ww w .  j  a  v a 2 s.c  o  m*/
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document document = builder.parse(nfoFile);

            // Optimise XML before proceeding to minimise errors
            document.getDocumentElement().normalize();

            if (document.getElementsByTagName("title").getLength() > 0) {
                if (!document.getElementsByTagName("title").item(0).getTextContent().equals("")) {
                    mediaElement.setTitle(document.getElementsByTagName("title").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("rating").getLength() > 0) {
                if (!document.getElementsByTagName("rating").item(0).getTextContent().equals("")) {
                    Float rating = Float
                            .valueOf(document.getElementsByTagName("rating").item(0).getTextContent());
                    mediaElement.setRating(rating);
                }
            }

            if (document.getElementsByTagName("year").getLength() > 0) {
                if (!document.getElementsByTagName("year").item(0).getTextContent().equals("")) {
                    Short year = Short
                            .parseShort(document.getElementsByTagName("year").item(0).getTextContent());
                    mediaElement.setYear(year);
                }
            }

            if (document.getElementsByTagName("genre").getLength() > 0) {
                if (!document.getElementsByTagName("genre").item(0).getTextContent().equals("")) {
                    mediaElement.setGenre(document.getElementsByTagName("genre").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("outline").getLength() > 0) {
                if (!document.getElementsByTagName("outline").item(0).getTextContent().equals("")) {
                    mediaElement
                            .setDescription(document.getElementsByTagName("outline").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("tagline").getLength() > 0) {
                if (!document.getElementsByTagName("tagline").item(0).getTextContent().equals("")) {
                    mediaElement.setTagline(document.getElementsByTagName("tagline").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("mpaa").getLength() > 0) {
                if (!document.getElementsByTagName("mpaa").item(0).getTextContent().equals("")) {
                    mediaElement.setCertificate(document.getElementsByTagName("mpaa").item(0).getTextContent());
                }
            }

            if (document.getElementsByTagName("set").getLength() > 0) {
                if (!document.getElementsByTagName("set").item(0).getTextContent().equals("")) {
                    mediaElement.setCollection(document.getElementsByTagName("set").item(0).getTextContent());
                }
            }
        } catch (ParserConfigurationException | SAXException | IOException e) {
            LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME,
                    "Unable to parse NFO file " + nfoFile.getPath(), e);
        }
    }

    return mediaElement;
}

From source file:gov.nih.nci.caintegrator.application.study.AnnotationGroupUploadContent.java

/**
 * @param version the version to set/*from   w  w  w.j  ava2 s  . co  m*/
 */
public void setVersion(String version) {
    if (!StringUtils.isBlank(version)) {
        this.version = Float.valueOf(version);
    }
}

From source file:communication.WeatherService.java

/** Find current weather at the given geographic point.
 * /*from   w  ww  .  j a v a2 s  .co m*/
 * @param lat
 * @param lon
 * @return
 * @throws IOException
 * @throws JSONException
 */
public Weather currentWeatherAtCoords(float lat, float lon) {
    try {
        String subUrl = String.format(Locale.ROOT, "weather?lat=%f&lon=%f", Float.valueOf(lat),
                Float.valueOf(lon));
        JSONObject response = doQuery(subUrl);
        return new Weather(response);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}