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:com.google.cloud.examples.coinflow.frontend.CoinflowServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    LOG.info("In CoinflowServlet doGet");

    if (req.getRequestURI().equals("/favicon.ico"))
        return;/*  w  ww.j  a va2  s  .  c om*/

    try (Table t = BigtableHelper.getConnection().getTable(TABLE)) {

        DateTime dateTime = new DateTime().minusHours(4);
        long before_ts = dateTime.getMillis();
        long now_ts = new DateTime().getMillis();

        String beforeRowKey = "match_" + before_ts;
        String afterRowKey = "match_" + now_ts;

        Scan scan = new Scan(beforeRowKey.getBytes(), afterRowKey.getBytes());
        ResultScanner rs = t.getScanner(scan);
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.setContentType("text/plain");

        List<PriceTimestamp> prices = new ArrayList<>();
        for (Result r : rs) {
            String data = new String(r.getValue(Schema.CF.getBytes(), Schema.QUALIFIER.getBytes()));
            CoinbaseData coinData = objectMapper.readValue(data, CoinbaseData.class);
            PriceTimestamp priceTimestamp = new PriceTimestamp(Float.parseFloat(coinData.getPrice()),
                    DateHelpers.convertDateToTime(coinData.getTime()));
            prices.add(priceTimestamp);
        }
        String pricesStr = objectMapper.writeValueAsString(prices);
        resp.getWriter().println(pricesStr);
    }

}

From source file:de.weltraumschaf.registermachine.asm.LineParser.java

private static float parseToFloat(final Token t) {
    return Float.parseFloat(t.getValue());
}

From source file:com.mycompany.controllers.BoardMemberController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createmember(@Valid BoardMemberForm boardMember, @PathVariable("idClub") String idClub,
        Model model) {/*from w ww .  jav  a2s . c o  m*/
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");
    SessionFactory factory = cfg.buildSessionFactory();

    //creating session object  
    Session session = factory.openSession();

    Transaction t = session.beginTransaction();

    Klub klub = session.find(Klub.class, Integer.parseInt(idClub));

    CzlonekZarzadu member = new CzlonekZarzadu();
    member.setImie(boardMember.getFirstName());
    member.setNazwisko(boardMember.getLastName());
    member.setStanowisko(boardMember.getPosition());
    member.setPensja(boardMember.getSalary());
    member.setProcentUdzialow(Float.parseFloat(String.valueOf(boardMember.getPercent())));
    member.setIdKlub(klub);

    session.persist(member);
    t.commit();

    session.close();
    factory.close();

    model.addAttribute("club", idClub);

    return new ModelAndView("redirect:/club/" + idClub + "/boardmembers/");

}

From source file:com.shahnami.fetch.Controller.FetchMovies.java

public List<Movie> getBollyMovies(String query) {
    try {/*from   w ww . j a v  a2 s  .c  o  m*/
        Document doc;
        Elements searchDetails;
        String link;
        String title;
        String image = null;
        Elements linkAndTitles;
        Document movieDetails;
        double rating = 0;
        String magnetLink;
        String torrentFile;
        NumberFormat formatter;
        String output;
        if (query.equalsIgnoreCase("")) {
            //
        } else {
            doc = Jsoup.connect("https://1337x.to/search/" + URLEncoder.encode(query, "UTF-8") + "+hindi/1/")
                    .userAgent("Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.7.2) Gecko/20040803").get();
            searchDetails = doc.getElementsByClass("coll-1");
            for (Element e : searchDetails) {
                linkAndTitles = e.getElementsByTag("strong");
                for (Element e1 : linkAndTitles) {
                    link = "https://1337x.to" + e1.getElementsByTag("a").first().attr("href");
                    title = e1.getElementsByTag("a").first().html();
                    if (!link.contains("/mirror")) {
                        Movie m = new Movie();
                        m.setTitle(title.replace("<b>", "").replace("</b>", "").trim()); //.substring(0, 47)+ "..."
                        m.setLanguage("Hindi");
                        m.setUrl(link);
                        Pattern pattern = Pattern.compile(".*([\\s(]+[0-9]{4}[\\s)]+).*");
                        Matcher matcher = pattern.matcher(title);
                        while (matcher.find()) {
                            m.setYear(Integer
                                    .parseInt(matcher.group(1).replace("(", "").replace(")", "").trim()));
                        }
                        movieDetails = Jsoup.connect(link).get();
                        try {
                            image = movieDetails.getElementsByClass("moive-box").first().getElementsByTag("img")
                                    .first().attr("src");
                            rating = Float.parseFloat(
                                    movieDetails.getElementsByClass("rateing").first().getElementsByTag("i")
                                            .attr("style").split(":")[1].replace("%;", "").trim());
                        } catch (Exception ex) {
                            //
                        }
                        magnetLink = movieDetails.getElementsByClass("magnet").first().attr("href");
                        torrentFile = movieDetails.getElementsByClass("torrent").first().attr("href");
                        formatter = NumberFormat.getNumberInstance();
                        formatter.setMinimumFractionDigits(2);
                        formatter.setMaximumFractionDigits(2);
                        output = formatter.format(rating / 10);
                        rating = Double.parseDouble(output);
                        if (rating < 1) {
                            rating = 0;
                        }
                        m.setRating(rating);
                        m.setSmall_cover_image(image);
                        List<Torrent> torrents = new ArrayList<>();
                        Torrent t = new Torrent();
                        t.setUrl(magnetLink);
                        Torrent t2 = new Torrent();
                        t2.setUrl(torrentFile);
                        torrents.add(t);
                        torrents.add(t2);
                        m.setTorrents(torrents);
                        m.getTorrents().get(0).setSeeds(
                                Integer.valueOf(movieDetails.getElementsByClass("green").first().text()));
                        m.getTorrents().get(0).setPeers(
                                Integer.valueOf(movieDetails.getElementsByClass("red").first().text()));
                        m.setIsBollywood(true);
                        m.setSize(movieDetails.getElementsByClass("list").first().getElementsByTag("li").get(3)
                                .text().substring(10).trim());
                        _movies.add(m);
                    }
                }
                //String link = linkAndTitle.getElementsByAttribute("href").first().text();
                //System.out.println(link);
                //String title = linkAndTitle.getElementsByTag("b").text();
                //System.out.println(title);
            }
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(FetchMovies.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FetchMovies.class.getName()).log(Level.SEVERE, null, ex);
    }
    return _movies;
}

From source file:ai.nitro.bot4j.bots.SeasonBot.java

@Override
protected void onReceiveAttachment(final UrlAttachmentReceivePayload payload, final Participant sender,
        Long botId) {/* w w  w.j  a  v  a2  s .  co m*/
    final Participant recipient = sender;
    ImageNetResult imageNetResult = null;

    Call<String> call = imageApi.postBase64Image(Long.toString(botId),
            getBase64ImageSendPayload(0, payload.getTitle(), payload.getUrl()));
    try {
        Response<String> response = call.execute();
        LOG.warn(response.body());
        Gson gson = new Gson();
        imageNetResult = gson.fromJson(response.body(), ImageNetResult.class);
    } catch (IOException e) {
        LOG.warn(e);
    }

    if (imageNetResult != null) {
        List<String> labels = imageNetResult.getLabels().subList(0, NR_RETURN_LABELS);
        List<String> probabilities = imageNetResult.getProbabilities().subList(0, NR_RETURN_LABELS);

        String label = labels.get(0);
        label = label.substring(0, 1).toUpperCase() + label.substring(1); //Capitalize first letter

        String reply = String.format("I am %s%s sure, that this image has been taken in %s.",
                (Float.parseFloat(probabilities.get(0)) * 100), '%', label);
        sendText(reply, recipient);
    } else {
        sendText("Something went wrong, please try again with another image.", recipient);
    }

    LOG.info("RECEIVED AN ATTACHMENT");

}

From source file:com.taobao.adfs.database.tdhsocket.client.util.ConvertUtil.java

public static float getFloatFromString(String stringVal) throws SQLException {
    if (StringUtils.isBlank(stringVal)) {
        return 0;
    }/* ww  w .java 2 s.  c o  m*/
    try {
        return Float.parseFloat(stringVal);
    } catch (NumberFormatException e) {
        throw new SQLException("Parse integer error:" + stringVal);
    }
}

From source file:IAAS.Monitoring.java

public void run() {
    Pve2Api api = new Pve2Api("192.168.100.10", "root", "pam", "pppppppp");
    //Iaas iaas = new Iaas();
    float percent;
    int var;
    List<Container> list = null;

    while (true) {
        try {//from  ww w.j  a  v  a  2  s.c  o  m
            list = api.getOpenvzCTs("proxmox");
        } catch (JSONException | LoginException | IOException ex) {
            Logger.getLogger(Monitoring.class.getName()).log(Level.SEVERE, null, ex);
        }
        Iterator<Container> it = list.iterator();
        while (it.hasNext()) {
            Container ct = it.next();
            percent = (Float.parseFloat(ct.getMem_usage()) * 100) / Float.parseFloat(ct.getMemory());
            System.out.println("vmID " + ct.getVmid());
            System.out.println("Memory Usage " + ct.getMem_usage());
            System.out.println("Memory " + ct.getMemory());
            System.out.println("percentage   " + percent);
            if (percent > 5) {
                try {
                    //reale value 70
                    var = Integer.parseInt(ct.getMemory()) / 1000000;
                    System.out.println("var   " + var);
                    System.out.println("var +1  " + (++var));
                    //updateTemplate(int container, int ram , int cpu)
                    updateContainer(Integer.parseInt(ct.getVmid()), var + 50, 0);
                    //ct.setMemory(var);
                    //iaas.UpdateContainer(ct);
                } catch (JSchException | IOException ex) {
                    Logger.getLogger(IaaSManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }

    }

}

From source file:ai.nitro.bot4j.bots.InceptionBot.java

@Override
protected void onReceiveAttachment(final UrlAttachmentReceivePayload payload, final Participant sender,
        Long botId) {//from   w w w.  j a  v a2s . co m
    final Participant recipient = sender;
    ImageNetResult imageNetResult = null;

    Call<String> call = imageApi.postBase64Image(Long.toString(botId),
            getBase64ImageSendPayload(0, payload.getTitle(), payload.getUrl()));

    try {
        Response<String> response = call.execute();

        LOG.warn(response.body());
        Gson gson = new Gson();
        imageNetResult = gson.fromJson(response.body(), ImageNetResult.class);
    } catch (IOException e) {
        LOG.warn(e);
    }

    if (imageNetResult != null) {
        List<String> labels = imageNetResult.getLabels().subList(0, NR_RETURN_LABELS);
        List<String> probabilities = imageNetResult.getProbabilities().subList(0, NR_RETURN_LABELS);

        String label = labels.get(0);
        label = label.substring(0, 1).toUpperCase() + label.substring(1); //Capitalize first letter

        String reply = String.format("This is very likely a %s. (Probability: %s%s)", label,
                (Float.parseFloat(probabilities.get(0)) * 100), '%');
        sendText(reply, recipient);
    } else {
        sendText("Something went wrong, please try again with another image.", recipient);
    }

    LOG.info("RECEIVED AN ATTACHMENT");

}

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

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

    // Save the simulation state
    _simState = simState;

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

    // Get the max location radius
    String maxRadiusStr = props.getProperty(_MAX_RADIUS_KEY);
    Validate.notEmpty(maxRadiusStr, "Max radius (key=" + _MAX_RADIUS_KEY + ") may not be empty");
    _maxRadius = Float.parseFloat(maxRadiusStr);
    _LOG.info("Using _maxRadius=[" + _maxRadius + "]");

    // Was a locations file supplied?
    String locationsFileStr = props.getProperty(_LOCATIONS_FILE_KEY);
    if ((null != locationsFileStr) && !locationsFileStr.equals("")) {
        // Yup
        loadLocations(locationsFileStr);
        _LOG.info("Using locations file [" + locationsFileStr + "]");
    }

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

From source file:com.ms.app.web.commons.tools.CurrencyFormattor.java

/**
 * /*w w  w  . j  ava  2  s.  c o  m*/
 * 
 * @param fen
 * @return
 */
public static int yuanTofen(String yuan) {
    try {
        float fen = Float.parseFloat(yuan);
        if (fen > 0) {
            return (int) (fen * 100 + 0.001f);
        }
    } catch (Exception e) {
    }
    return 0;
}