Example usage for java.lang Float parseFloat

List of usage examples for java.lang Float parseFloat

Introduction

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

Prototype

public static float parseFloat(String s) throws NumberFormatException 

Source Link

Document

Returns a new float initialized to the value represented by the specified String , as performed by the valueOf method of class Float .

Usage

From source file:blue.soundObject.pianoRoll.PianoNote.java

public static PianoNote loadFromXML(Element data) {
    PianoNote note = new PianoNote();

    Elements nodes = data.getElements();

    while (nodes.hasMoreElements()) {
        Element node = nodes.next();

        if (node.getName().equals("octave")) {
            note.setOctave(Integer.parseInt(node.getTextString()));
        } else if (node.getName().equals("scaleDegree")) {
            note.setScaleDegree(Integer.parseInt(node.getTextString()));
        } else if (node.getName().equals("start")) {
            note.setStart(Float.parseFloat(node.getTextString()));
        } else if (node.getName().equals("duration")) {
            note.setDuration(Float.parseFloat(node.getTextString()));
        } else if (node.getName().equals("noteTemplate")) {
            note.setNoteTemplate(node.getTextString());
        }/*from w  w w . j a  v a2 s  . c om*/
    }

    return note;
}

From source file:draw.chemy.JSONLoader.java

private List<Path> createPath(String aPath) {
    StringTokenizer tokenizer = new StringTokenizer(aPath);
    List<Path> result = new ArrayList<Path>();
    List<PointF> tempPointFs = new ArrayList<PointF>();
    SVGPathCommand currentOp = null;// www .j  a  v  a  2s  . c  o m
    PointF lastPointF = new PointF(0f, 0f);
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if (token.contains(",")) {
            String[] split = token.split(",");
            PointF PointF = new PointF(Float.parseFloat(split[0]), Float.parseFloat(split[1]));
            tempPointFs.add(PointF);
        } else if (fSVGCommands.containsKey(token)) {
            if (currentOp != null) {
                currentOp.operation(tempPointFs, result, lastPointF);
            }
            currentOp = fSVGCommands.get(token);
            tempPointFs.clear();
        }
    }
    if (currentOp != null) {
        currentOp.operation(tempPointFs, result, lastPointF);
    }
    return result;
}

From source file:com.streamsets.datacollector.record.FieldDeserializer.java

@SuppressWarnings("unchecked")
private Field parse(Map<String, Object> map) {
    Field field = null;//from   ww w  . j a v  a2 s.  com
    if (map != null) {
        Field.Type type = Field.Type.valueOf((String) map.get("type"));
        Object value = map.get("value");
        if (value != null) {
            switch (type) {
            case MAP:
                Map<String, Field> fMap = new HashMap<>();
                for (Map.Entry<String, Object> entry : ((Map<String, Object>) value).entrySet()) {
                    fMap.put(entry.getKey(), parse((Map<String, Object>) entry.getValue()));
                }
                value = fMap;
                break;
            case LIST:
                List<Field> fList = new ArrayList<>();
                for (Map<String, Object> element : (List<Map<String, Object>>) value) {
                    fList.add(parse(element));
                }
                value = fList;
                break;
            case LIST_MAP:
                //When converting list to listMap, Key for the listMap is recovered using path attribute
                Map<String, Field> listMap = new LinkedHashMap<>();
                for (Map<String, Object> element : (List<Map<String, Object>>) value) {
                    String path = (String) element.get("sqpath");
                    listMap.put(EscapeUtil.getLastFieldNameFromPath(path), parse(element));
                }
                value = listMap;
                break;
            case BYTE_ARRAY:
                value = Base64.decodeBase64((String) value);
                break;
            case INTEGER:
                value = Integer.parseInt((String) value);
                break;
            case LONG:
                value = Long.parseLong((String) value);
                break;
            case FLOAT:
                value = Float.parseFloat((String) value);
                break;
            case DOUBLE:
                value = Double.parseDouble((String) value);
                break;
            default:
                break;
            }
        }
        field = Field.create(type, value);
    }
    return field;
}

From source file:com.ultrapower.eoms.common.plugin.ecside.util.ECSideUtils.java

 public static float parseFloat(String value) {
   float result = 0.0f;
   try {/*from w w  w. j a  v  a 2 s . com*/
      result = Float.parseFloat(value);
   } catch (Exception ex) {
   }
   return result;
}

From source file:edu.snu.leader.discrete.simulator.Predator.java

public void initialize(SimulationState simState) {
    _simState = simState;/*from  w  ww. j  av a 2 s  .c  o m*/

    // get values from properties
    String stringMaxAgentsEatenPerStep = _simState.getProperties().getProperty("max-agents-eaten-per-step");
    Validate.notEmpty(stringMaxAgentsEatenPerStep, "max agents eater per step may not be empty");
    _maxAgentsEatenPerStep = Integer.parseInt(stringMaxAgentsEatenPerStep);

    String stringPredationMultiplier = _simState.getProperties().getProperty("predation-multiplier");
    Validate.notEmpty(stringPredationMultiplier, "predation multiplier required");
    _predationMultiplier = Double.parseDouble(stringPredationMultiplier);

    String stringUsePredationThreshold = _simState.getProperties().getProperty("use-predation-threshold");
    Validate.notEmpty(stringUsePredationThreshold, "use predation threshold required");
    _usePredationThreshold = Boolean.parseBoolean(stringUsePredationThreshold);

    String stringPredationThreshold = _simState.getProperties().getProperty("predation-threshold");
    Validate.notEmpty(stringPredationThreshold, "predation threshold required");
    _predationThreshold = Float.parseFloat(stringPredationThreshold);

    String stringPredationByPopulation = _simState.getProperties().getProperty("predation-by-population");
    Validate.notEmpty(stringPredationByPopulation, "predation by population required");
    _usePredationByPopulation = Boolean.parseBoolean(stringPredationByPopulation);

    String stringPredationProbabilityMinimum = _simState.getProperties()
            .getProperty("predation-probability-minimum");
    Validate.notEmpty(stringPredationProbabilityMinimum, "predation probability minumum required");
    _predationProbabilityMinimum = Double.parseDouble(stringPredationProbabilityMinimum);

    // add agents to the predator so it knows of them
    _agents = new ArrayList<Agent>(_simState.getAgentCount());
    Iterator<Agent> iter = _simState.getAgentIterator();
    while (iter.hasNext()) {
        _agents.add(iter.next());
    }

    _predationEvents = new ArrayList<PredationEvent>(_agents.size());
}

From source file:org.mstc.zmq.json.Decoder.java

@SuppressWarnings("unchecked")
public static void decode(String input, Field[] fields, Object b) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    if (logger.isDebugEnabled())
        logger.debug(input);/*ww  w . j a  va  2  s .  co m*/
    JsonFactory factory = mapper.getFactory();
    try (JsonParser jp = factory.createParser(input)) {
        /* Sanity check: verify that we got "Json Object" */
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }

        /* Iterate over object fields */
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            jp.nextToken();
            Field field = getField(fieldName, fields);
            if (field == null) {
                throw new IOException(
                        "Could not find field [" + fieldName + "] on class " + b.getClass().getName());
            }
            try {
                if (field.getType().isAssignableFrom(List.class)) {
                    String adder = getAdder(fieldName);
                    TypeFactory t = TypeFactory.defaultInstance();
                    ParameterizedType listType = (ParameterizedType) field.getGenericType();
                    Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];
                    List list = mapper.readValue(jp.getValueAsString(),
                            t.constructCollectionType(List.class, listClass));
                    Method m = b.getClass().getDeclaredMethod(adder, Collection.class);
                    m.invoke(b, list);
                } else if (field.getType().isArray()) {
                    Class<?> type = field.getType();
                    String setter = getSetter(fieldName);
                    Method m = b.getClass().getDeclaredMethod(setter, field.getType());
                    logger.info("Field {} is array of {}[], {}, using method {}", field.getName(),
                            field.getType().getComponentType(), jp.getCurrentToken().name(), m);
                    if (jp.getCurrentToken().id() == JsonToken.START_ARRAY.id()) {
                        List list = new ArrayList();
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            String value = jp.getText();
                            switch (jp.getCurrentToken()) {
                            case VALUE_STRING:
                                list.add(value);
                                break;
                            case VALUE_NUMBER_INT:
                                if (type.getComponentType().isAssignableFrom(double.class)) {
                                    list.add(Double.parseDouble(value));
                                } else if (type.getComponentType().isAssignableFrom(float.class)) {
                                    list.add(Float.parseFloat(value));
                                } else {
                                    list.add(Integer.parseInt(value));
                                }
                                break;
                            case VALUE_NUMBER_FLOAT:
                                logger.info("Add float");
                                list.add(jp.getFloatValue());
                                break;
                            case VALUE_NULL:
                                break;
                            default:
                                logger.warn("[3] Not sure how to handle {} yet", jp.getCurrentToken().name());
                            }
                        }
                        Object array = Array.newInstance(field.getType().getComponentType(), list.size());
                        for (int i = 0; i < list.size(); i++) {
                            Object val = list.get(i);
                            Array.set(array, i, val);
                        }
                        m.invoke(b, array);
                    } else {
                        if (type.getComponentType().isAssignableFrom(byte.class)) {
                            m.invoke(b, jp.getBinaryValue());
                        }
                    }
                } else {
                    String setter = getSetter(fieldName);
                    logger.debug("{}: {}", setter, field.getType().getName());
                    Method m = b.getClass().getDeclaredMethod(setter, field.getType());

                    switch (jp.getCurrentToken()) {
                    case VALUE_STRING:
                        m.invoke(b, jp.getText());
                        break;
                    case VALUE_NUMBER_INT:
                        m.invoke(b, jp.getIntValue());
                        break;
                    case VALUE_NUMBER_FLOAT:
                        m.invoke(b, jp.getFloatValue());
                        break;
                    case VALUE_NULL:
                        logger.debug("Skip invoking {}.{}, property is null", b.getClass().getName(),
                                m.getName());
                        break;
                    case START_OBJECT:
                        StringBuilder sb = new StringBuilder();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            switch (jp.getCurrentToken()) {
                            case VALUE_STRING:
                                sb.append("\"").append(jp.getText()).append("\"");
                                break;
                            case FIELD_NAME:
                                if (sb.length() > 0)
                                    sb.append(",");
                                sb.append("\"").append(jp.getText()).append("\"").append(":");
                                break;
                            case VALUE_NUMBER_INT:
                                sb.append(jp.getIntValue());
                                break;
                            case VALUE_NUMBER_FLOAT:
                                sb.append(jp.getFloatValue());
                                break;
                            case VALUE_NULL:
                                sb.append("null");
                                break;
                            default:
                                logger.warn("[2] Not sure how to handle {} yet", jp.getCurrentToken().name());
                            }
                        }
                        String s = String.format("%s%s%s", JsonToken.START_OBJECT.asString(), sb.toString(),
                                JsonToken.END_OBJECT.asString());
                        Object parsed = getNested(field.getType(), s.getBytes());
                        m.invoke(b, parsed);
                        break;
                    default:
                        logger.warn("[1] Not sure how to handle {} yet", jp.getCurrentToken().name());
                    }
                }
            } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException
                    | IllegalArgumentException e) {
                logger.error("Failed setting field [{}], builder: {}", fieldName, b.getClass().getName(), e);
            }
        }
    }
}

From source file:carmen.utils.CommandLineUtilities.java

public static float getOptionValueAsFloat(String option) {
    String value = CommandLineUtilities.getOptionValue(option);
    if (value != null)
        return Float.parseFloat(value);
    return -1;/*from  w  w  w  . jav a 2  s .  co  m*/
}

From source file:com.hp.mqm.clt.xml.JunitXmlIterator.java

private long parseTime(String timeString) {
    try {//www . j av  a  2s  . c o  m
        float seconds = Float.parseFloat(timeString);
        return (long) (seconds * 1000);
    } catch (NumberFormatException e) {
        System.out.println("Unable to parse test duration: " + timeString);
    }
    return 0;
}

From source file:hivemall.classifier.ConfidenceWeightedUDTF.java

@Override
protected CommandLine processOptions(ObjectInspector[] argOIs) throws UDFArgumentException {
    final CommandLine cl = super.processOptions(argOIs);

    float phi = 1.f;
    if (cl != null) {
        String phi_str = cl.getOptionValue("phi");
        if (phi_str == null) {
            String eta_str = cl.getOptionValue("eta");
            if (eta_str != null) {
                double eta = Double.parseDouble(eta_str);
                if (eta <= 0.5 || eta > 1) {
                    throw new UDFArgumentException(
                            "Confidence hyperparameter eta must be in range (0.5, 1]: " + eta_str);
                }//from   w  w w  .  ja v a  2  s. com
                phi = (float) StatsUtils.probit(eta, 5d);
            }
        } else {
            phi = Float.parseFloat(phi_str);
        }
    }

    this.phi = phi;
    return cl;
}

From source file:com.google.template.soy.i18ndirectives.FormatNumDirective.java

@Override
public SoyData apply(SoyData value, List<SoyData> args) {
    Locale locale = I18nUtils.parseLocale(localeStringProvider.get());
    NumberFormat instance;/* w  w w . j  a  v a  2s .c  o m*/
    String formatType = args.isEmpty() ? "decimal" : args.get(0).stringValue();

    if (formatType.equals("decimal")) {
        instance = NumberFormat.getInstance(locale);
    } else if (formatType.equals("percent")) {
        instance = NumberFormat.getPercentInstance(locale);
    } else if (formatType.equals("currency")) {
        instance = NumberFormat.getCurrencyInstance(locale);
    } else if (formatType.equals("scientific")) {
        instance = NumberFormat.getScientificInstance(locale);
    } else {
        throw new IllegalArgumentException(String.format("Unrecognized Number Format Type: {0}", formatType));
    }
    return toSoyData(StringEscapeUtils.escapeHtml4(instance.format(Float.parseFloat(value.stringValue()))));
}