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:at.favre.tools.dconvert.ui.CLIInterpreter.java

public static Arguments parse(String[] args) {
    ResourceBundle strings = ResourceBundle.getBundle("bundles.strings", Locale.getDefault());
    Options options = setupOptions(strings);
    CommandLineParser parser = new DefaultParser();

    Arguments.Builder builder;/*  w ww .  j av  a 2s .co m*/
    try {
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption("gui")) {
            return Arguments.START_GUI;
        }

        if (commandLine.hasOption("h") || commandLine.hasOption("help")) {
            printHelp(options);
            return null;
        }

        if (commandLine.hasOption("v") || commandLine.hasOption("version")) {
            System.out.println("Version: " + CLIInterpreter.class.getPackage().getImplementationVersion());
            return null;
        }

        String scaleRawParam = commandLine.getOptionValue(SCALE_ARG).toLowerCase();

        boolean dp = false;

        if (scaleRawParam.contains("dp")) {
            dp = true;
            scaleRawParam = scaleRawParam.replace("dp", "").trim();
        }

        builder = new Arguments.Builder(new File(commandLine.getOptionValue(SOURCE_ARG)),
                Float.parseFloat(scaleRawParam));

        if (dp && commandLine.hasOption(SCALE_IS_HEIGHT_DP_ARG)) {
            builder.scaleMode(EScaleMode.DP_HEIGHT);
        } else if (dp && !commandLine.hasOption(SCALE_IS_HEIGHT_DP_ARG)) {
            builder.scaleMode(EScaleMode.DP_WIDTH);
        } else {
            builder.scaleMode(EScaleMode.FACTOR);
        }

        if (commandLine.hasOption(DST_ARG)) {
            builder.dstFolder(new File(commandLine.getOptionValue(DST_ARG)));
        }

        float compressionQuality = Arguments.DEFAULT_COMPRESSION_QUALITY;
        if (commandLine.hasOption(COMPRESSION_QUALITY_ARG)) {
            compressionQuality = Float.valueOf(commandLine.getOptionValue(COMPRESSION_QUALITY_ARG));
        }

        if (commandLine.hasOption(OUT_COMPRESSION_ARG)) {
            switch (commandLine.getOptionValue(OUT_COMPRESSION_ARG)) {
            case "strict":
                builder.compression(EOutputCompressionMode.SAME_AS_INPUT_STRICT);
                break;
            case "png":
                builder.compression(EOutputCompressionMode.AS_PNG);
                break;
            case "jpg":
                builder.compression(EOutputCompressionMode.AS_JPG, compressionQuality);
                break;
            case "gif":
                builder.compression(EOutputCompressionMode.AS_GIF);
                break;
            case "bmp":
                builder.compression(EOutputCompressionMode.AS_BMP);
                break;
            case "png+jpg":
                builder.compression(EOutputCompressionMode.AS_JPG_AND_PNG, compressionQuality);
                break;
            default:
                System.err.println(
                        "unknown compression type: " + commandLine.getOptionValue(OUT_COMPRESSION_ARG));
            }
        }

        Set<EPlatform> platformSet = new HashSet<>(EPlatform.values().length);
        if (commandLine.hasOption(PLATFORM_ARG)) {
            switch (commandLine.getOptionValue(PLATFORM_ARG)) {
            case "all":
                platformSet = EPlatform.getAll();
                break;
            case "android":
                platformSet.add(EPlatform.ANDROID);
                break;
            case "ios":
                platformSet.add(EPlatform.IOS);
                break;
            case "win":
                platformSet.add(EPlatform.WINDOWS);
                break;
            case "web":
                platformSet.add(EPlatform.WEB);
                break;
            default:
                System.err.println("unknown mode: " + commandLine.getOptionValue(PLATFORM_ARG));
            }
            builder.platform(platformSet);
        }

        if (commandLine.hasOption(UPSCALING_ALGO_ARG)) {
            builder.upScaleAlgorithm(
                    EScalingAlgorithm.getByName(commandLine.getOptionValue(UPSCALING_ALGO_ARG)));
        }

        if (commandLine.hasOption(DOWNSCALING_ALGO_ARG)) {
            builder.upScaleAlgorithm(
                    EScalingAlgorithm.getByName(commandLine.getOptionValue(DOWNSCALING_ALGO_ARG)));
        }

        if (commandLine.hasOption(ROUNDING_MODE_ARG)) {
            switch (commandLine.getOptionValue(ROUNDING_MODE_ARG)) {
            case "round":
                builder.scaleRoundingStragy(RoundingHandler.Strategy.ROUND_HALF_UP);
                break;
            case "ceil":
                builder.scaleRoundingStragy(RoundingHandler.Strategy.CEIL);
                break;
            case "floor":
                builder.scaleRoundingStragy(RoundingHandler.Strategy.FLOOR);
                break;
            default:
                System.err.println("unknown mode: " + commandLine.getOptionValue(ROUNDING_MODE_ARG));
            }
        }

        if (commandLine.hasOption(THREADS_ARG)) {
            builder.threadCount(Integer.valueOf(commandLine.getOptionValue(THREADS_ARG)));
        }

        builder.skipUpscaling(commandLine.hasOption("skipUpscaling"));
        builder.skipExistingFiles(commandLine.hasOption(SKIP_EXISTING_ARG));
        builder.includeAndroidLdpiTvdpi(commandLine.hasOption("androidIncludeLdpiTvdpi"));
        builder.verboseLog(commandLine.hasOption(VERBOSE_ARG));
        builder.haltOnError(commandLine.hasOption("haltOnError"));
        builder.createMipMapInsteadOfDrawableDir(commandLine.hasOption("androidMipmapInsteadOfDrawable"));
        builder.antiAliasing(commandLine.hasOption("antiAliasing"));
        builder.enablePngCrush(commandLine.hasOption("postProcessorPngCrush"));
        builder.postConvertWebp(commandLine.hasOption("postProcessorWebp"));
        builder.dryRun(commandLine.hasOption("dryRun"));
        builder.enableMozJpeg(commandLine.hasOption("postProcessorMozJpeg"));
        builder.keepUnoptimizedFilesPostProcessor(commandLine.hasOption("keepOriginalPostProcessedFiles"));
        builder.iosCreateImagesetFolders(commandLine.hasOption("iosCreateImagesetFolders"));
        builder.clearDirBeforeConvert(commandLine.hasOption("clean"));

        return builder.build();
    } catch (Exception e) {
        System.err.println("Could not parse args: " + e.getMessage());
    }
    return null;
}

From source file:com.pivotal.gfxd.demo.loader.Loader.java

public void insertBatch(final List<String[]> lines, final long timestamp) {
    String sql = "insert into raw_sensor (id, timestamp, value, property, plug_id, household_id, house_id, weekday, time_slice) values (?,?,?,?,?,?,?,?,?)";
    final Calendar cal = Calendar.getInstance();

    getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
        @Override/* w w w . j  a  v  a  2s . c  o  m*/
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            final String[] split = lines.get(i);
            int plugId = Integer.parseInt(split[4]);
            int householdId = Integer.parseInt(split[5]);
            int houseId = Integer.parseInt(split[6]);

            ps.setLong(1, Long.parseLong(split[0]));
            ps.setLong(2, timestamp);
            float value = Float.parseFloat(split[2]);
            ps.setFloat(3, value + value * disturbance);
            ps.setInt(4, Integer.parseInt(split[3]));
            ps.setInt(5, computePlugId(plugId, householdId, houseId));
            ps.setInt(6, householdId);
            ps.setInt(7, houseId);

            cal.setTimeInMillis(timestamp * 1000L);
            int weekDay = cal.get(Calendar.DAY_OF_WEEK);
            int timeSlice = (cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE))
                    / MINUTES_PER_INTERVAL;

            ps.setInt(8, weekDay); // weekday
            ps.setInt(9, timeSlice); // time_slice
        }

        @Override
        public int getBatchSize() {
            return lines.size();
        }
    });

    cal.setTimeInMillis(timestamp * 1000L);
    int weekDay = cal.get(Calendar.DAY_OF_WEEK);
    int timeSlice = (cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE)) / MINUTES_PER_INTERVAL;

    LOG.debug("rows=" + lines.size() + " weekday=" + weekDay + " slice=" + timeSlice + " stamp=" + timestamp
            + " now=" + (int) (System.currentTimeMillis() / 1000));

    rowsInserted += lines.size();
}

From source file:org.opens.color.finder.webapp.validator.ColorModelValidator.java

private Float isValidRatio(String ratio) {
    try {// w  w w .  j  a  va2s  .  c  o m
        Float.parseFloat(ratio);
    } catch (NumberFormatException nfe) {
        return 0.0f;
    }
    Float coeff = Float.valueOf(ratio);
    if (coeff >= MIN_VALID_RATIO && coeff <= MAX_VALID_RATIO) {
        return coeff;
    } else {
        return Float.valueOf(0.0f);
    }
}

From source file:SAXSample.java

public void characters(char[] ch, int start, int length) {
    String chars = new String(ch, start, length).trim();
    if (chars.length() == 0) {
        return;//from   www . j  a  v  a2 s . com
    }

    SAXBook book = books.getLastBook();
    if (readingAuthor) {
        book.setAuthor(chars);
    } else if (readingTitle) {
        book.setTitle(chars);
    } else if (readingPrice) {
        book.setPrice(Float.parseFloat(chars));
    }
}

From source file:account.management.controller.inventory.InsertStockController.java

/**
 * Initializes the controller class./*from   w  w w . j av  a 2s.  c  o m*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    // get product list
    products_list = FXCollections.observableArrayList();
    try {
        HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "all/products").asJson();
        JSONArray array = res.getBody().getArray();
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            int id = obj.getInt("id");
            String name = obj.getString("name");
            float p_qty = Float.parseFloat(obj.get("p_qty").toString());
            float s_qty = Float.parseFloat(obj.get("s_qty").toString());
            double last_p_rate = obj.getDouble("last_p_rate");
            double last_s_rate = obj.getDouble("last_s_rate");
            double avg_p_rate = obj.getDouble("avg_p_rate");
            double avg_s_rate = obj.getDouble("avg_s_rate");

            products_list
                    .add(new Product(id, name, p_qty, s_qty, last_p_rate, last_s_rate, avg_p_rate, avg_s_rate));

        }

        addRow();

    } catch (Exception e) {
    }

    // voucher type (purchase/sell)
    this.voucher_type.getItems().addAll("Purchase", "Sell");
    this.voucher_type.getSelectionModel().select("Sell");

}

From source file:edu.cornell.med.icb.geo.ParseAffymetrixSampleDataCallback.java

@Override
public void parse(final MutableString line) {
    final int probeIndex = getProbeIndex(line);
    final String[] tokens = spaceSplitter.split(line.toString(), 0);
    if (tokens.length <= signalColumnIndex || tokens[signalColumnIndex].length() == 0) {
        // stop if no signal because NC/ No Call instead.
        return;/*from w  ww.ja v  a  2 s .  c  om*/
    }
    float signalValue = 0;
    try {
        signalValue = Float.parseFloat(tokens[signalColumnIndex]);

        boolean present = false;
        if (presenceAbsenceColumnIndex < tokens.length && presenceAbsencePValueColumnIndex < tokens.length) {
            present = presenceAbsenceColumnIndex != -1
                    ? determinePresenceCall(tokens[presenceAbsenceColumnIndex])
                    : presenceAbsencePValueColumnIndex != -1
                            ? determinePresenceCallPValue(tokens[presenceAbsencePValueColumnIndex])
                            : signalValue > signalThresholdForDetection;
        } else {
            present = signalValue > signalThresholdForDetection;
        }

        if (probeIndex != -1) {
            parsedData.signal[probeIndex] = signalValue;
            parsedData.presentAbsentCalls.set(probeIndex, present);
        }
    } catch (NumberFormatException e) {
        LOG.debug("Cannot parse signal value " + tokens[signalColumnIndex]);
    }
}

From source file:com.frostwire.gui.library.tags.MPlayerParser.java

private int parseDuration(String durationInSecs) {
    try {//from ww  w.jav  a  2  s . com
        return (int) Float.parseFloat(durationInSecs);
    } catch (Exception e) {
        return 0;
    }
}

From source file:edu.snu.leader.hidden.builder.BiDirectionalIndividualBuilder.java

/**
 * Initializes the builder/*from  w  ww. java2s .  c  o m*/
 *
 * @param simState The simulation's state
 * @see edu.snu.leader.hidden.builder.AbstractIndividualBuilder#initialize(edu.snu.leader.hidden.SimulationState)
 */
@Override
public void initialize(SimulationState simState) {
    _LOG.trace("Entering initialize( simState )");

    // Call the superclass implementation
    super.initialize(simState);

    // Get the properties
    Properties props = simState.getProps();

    // Get the direction delta value
    String dirDeltaStr = props.getProperty(_DIR_DELTA_KEY);
    Validate.notEmpty(dirDeltaStr, "Direction delta (key=" + _DIR_DELTA_KEY + ") may not be empty");
    _dirDelta = Float.parseFloat(dirDeltaStr);
    _LOG.info("Using _dirDelta=[" + _dirDelta + "]");

    // Get the positive delta probability
    String posDeltaProbabilityStr = props.getProperty(_POS_DELTA_PROB_KEY);
    Validate.notEmpty(posDeltaProbabilityStr,
            "Positive delta percentage (key=" + _POS_DELTA_PROB_KEY + ") may not be empty");
    _positiveDeltaProbability = Float.parseFloat(posDeltaProbabilityStr);
    _LOG.info("Using _dirDelta=[" + _positiveDeltaProbability + "]");

    _LOG.trace("Leaving initialize( simState )");
}

From source file:com.ratebeer.android.api.command.GetPlaceDetailsCommand.java

@Override
protected void parse(JSONArray json) throws JSONException {

    JSONObject result = json.getJSONObject(0);
    String percentile = result.getString("Percentile");

    // Get the details directly form the JSON object
    details = new Place(result.getInt("PlaceID"), HttpHelper.cleanHtml(result.getString("PlaceName")),
            result.getInt("PlaceType"), HttpHelper.cleanHtml(result.getString("Address")),
            HttpHelper.cleanHtml(result.getString("City")), result.getString("StateID"),
            result.getInt("CountryID"), HttpHelper.cleanHtml(result.getString("PostalCode")),
            HttpHelper.cleanHtml(result.getString("PhoneNumber")),
            percentile.equals("null") ? -1 : (int) Float.parseFloat(percentile),
            result.isNull("RateCount") ? 0 : result.getInt("RateCount"),
            HttpHelper.cleanHtml(result.getString("PhoneAC")), result.getDouble("Latitude"),
            result.getDouble("Longitude"), -1D);

}

From source file:pe.gob.mef.gescon.service.impl.ConsultaServiceImpl.java

@Override
public List<Consulta> getQueryFilter(HashMap filters) {
    List<Consulta> lista = new ArrayList<Consulta>();
    try {/*  w ww  . j  a  v  a2  s.  c  om*/
        ConsultaDao consultaDao = (ConsultaDao) ServiceFinder.findBean("ConsultaDao");
        List<HashMap> consulta = consultaDao.getQueryFilter(filters);
        if (!CollectionUtils.isEmpty(consulta)) {
            for (HashMap map : consulta) {
                Consulta c = new Consulta();
                c.setIdconocimiento((BigDecimal) map.get("ID"));
                c.setNombre((String) map.get("NOMBRE"));
                c.setSumilla((String) map.get("SUMILLA"));
                c.setFechaPublicacion((Date) map.get("FECHA"));
                c.setIdCategoria((BigDecimal) map.get("IDCATEGORIA"));
                c.setCategoria((String) map.get("CATEGORIA"));
                c.setIdTipoConocimiento((BigDecimal) map.get("IDTIPOCONOCIMIENTO"));
                c.setTipoConocimiento((String) map.get("TIPOCONOCIMIENTO"));
                c.setIdEstado((BigDecimal) map.get("IDESTADO"));
                c.setEstado((String) map.get("ESTADO"));
                c.setFlgVinculo((BigDecimal) map.get("FLG"));
                BigDecimal contador = (BigDecimal) map.get("CONTADOR");
                BigDecimal suma = (BigDecimal) map.get("SUMA");
                if (BigDecimal.ZERO.equals(contador)) {
                    c.setCalificacion(BigDecimal.ZERO.intValue());
                } else {
                    int calificacion = Math
                            .round(Float.parseFloat(suma.toString()) / Integer.parseInt(contador.toString()));
                    c.setCalificacion(calificacion);
                }
                lista.add(c);
            }
        }
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return lista;
}