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.jkoolcloud.tnt4j.logger.AppenderTools.java

/**
 * Convert annotated value with key type qualifier such as %type/
 * into key, value property.// w w w  .  j a  va2  s.  co  m
 * <table>
 * <tr><td><b>%[s|i|l|f|d|n|b][:value-type]/user-key</b></td><td>User defined key/value pair and [s|i|l|f|n|d|b] are type specifiers (i=Integer, l=Long, d=Double, f=Float, n=Number, s=String, b=Boolean) (e.g #%i/myfield=7634732)</td></tr>
 * </table>
 *
 * @param key key with prefixed type qualifier
 * @param value to be converted based on type qualifier
 *
 * @return property containing key and value
 */
public static Property toProperty(String key, String value) {
    Object pValue = value;

    try {
        if (!key.startsWith(TAG_TYPE_QUALIFIER)) {
            // if no type specified, assume a numeric field
            pValue = Long.parseLong(value);
        } else if (key.startsWith(TAG_TYPE_STRING)) {
            pValue = value;
        } else if (key.startsWith(TAG_TYPE_NUMBER)) {
            pValue = Double.parseDouble(value);
        } else if (key.startsWith(TAG_TYPE_INTEGER)) {
            pValue = Integer.parseInt(value);
        } else if (key.startsWith(TAG_TYPE_LONG)) {
            pValue = Long.parseLong(value);
        } else if (key.startsWith(TAG_TYPE_FLOAT)) {
            pValue = Float.parseFloat(value);
        } else if (key.startsWith(TAG_TYPE_DOUBLE)) {
            pValue = Double.parseDouble(value);
        } else if (key.startsWith(TAG_TYPE_BOOLEAN)) {
            pValue = Boolean.parseBoolean(value);
        }
    } catch (NumberFormatException ne) {
    }
    return new Property(getKey(key), pValue, getValueType(key));
}

From source file:com.autentia.intra.manager.admin.SettingManager.java

/**
 * Get a property value as float/* w  ww .  j av  a  2 s . c  o m*/
 *
 * @param propertyPath property path
 * @param defaultValue default value for property
 * @return property value
 */
public static float getFloat(Setting val, float defaultValue) {

    return (val == null || val.getValue() == null) ? defaultValue : Float.parseFloat(val.getValue());
}

From source file:com.linkedin.cubert.io.text.TextTupleCreator.java

@Override
public Tuple create(Object key, Object value) throws ExecException {
    Text t = (Text) value;
    String[] fields = t.toString().split(separator);

    for (int i = 0; i < fields.length; i++) {
        Object obj = null;/*from www  . j  a va  2  s. c  om*/

        if (fields[i] != null && fields[i].length() != 0)
            switch (typeArray[i]) {
            case INT:
                obj = new Integer(Integer.parseInt(fields[i]));
                break;

            case LONG:
                obj = new Long(Long.parseLong(fields[i]));
                break;

            case STRING:
                obj = fields[i];
                break;

            case DOUBLE:
                obj = Double.parseDouble(fields[i]);
                break;

            case FLOAT:
                obj = Float.parseFloat(fields[i]);
                break;
            default:
                break;
            }

        tuple.set(i, obj);
    }

    return tuple;
}

From source file:account.management.controller.LCReportController.java

@Override
public void initialize(URL url, ResourceBundle rb) {

    new AutoCompleteComboBoxListener<>(select_lc);
    select_lc.setOnHiding((e) -> {/*from  w ww.  j av  a 2  s.co m*/
        LC a = select_lc.getSelectionModel().getSelectedItem();
        select_lc.setEditable(false);
        select_lc.getSelectionModel().select(a);
    });
    select_lc.setOnShowing((e) -> {
        select_lc.setEditable(true);
    });

    lc = FXCollections.observableArrayList();
    new Thread(() -> {
        try {
            HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "get/lc/all").asJson();
            JSONArray array = res.getBody().getArray();

            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                long id = obj.getLong("id");
                String lc_no = obj.get("lc_number").toString();
                String party_name = obj.getString("party_name");
                String party_bank = obj.getString("party_bank_name");
                String party_address = obj.getString("party_address");
                String our_bank = obj.getString("our_bank_name");
                String lc_amount = String.valueOf(Float.parseFloat(obj.getString("lc_amount")));
                String init_date = obj.getString("initialing_date");
                String start_date = obj.getString("starting_date");
                String dimilish_date = obj.getString("dimilish_date");

                lc.add(new LC(id, lc_no, party_name, party_bank, party_address, our_bank, lc_amount, init_date,
                        start_date, dimilish_date));

            }

        } catch (UnirestException ex) {
            Logger.getLogger(LCReportController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            this.select_lc.getItems().addAll(lc);
        }
    }).start();
}

From source file:hivemall.regression.PassiveAggressiveRegressionUDTF.java

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

    float c = aggressiveness();
    float epsilon = 0.1f;

    if (cl != null) {
        String opt_c = cl.getOptionValue("c");
        if (opt_c != null) {
            c = Float.parseFloat(opt_c);
            if (!(c > 0.f)) {
                throw new UDFArgumentException("Aggressiveness parameter C must be C > 0: " + c);
            }//from   w w  w  . j  a  v  a 2s  .co m
        }

        String opt_epsilon = cl.getOptionValue("epsilon");
        if (opt_epsilon != null) {
            epsilon = Float.parseFloat(opt_epsilon);
        }
    }

    this.c = c;
    this.epsilon = epsilon;
    return cl;
}

From source file:strat.mining.multipool.stats.jersey.client.impl.BitstampCurrencyTickerClient.java

@Override
public CurrencyTickerDTO getCurrencyTicker(String currencyCode) {
    CurrencyTickerDTO result = new CurrencyTickerDTO();
    try {/*  w  w  w  .  j a  v  a  2 s . com*/
        LOGGER.debug("Retrieving ticker from Bitstamp for currency USD.");
        long start = System.currentTimeMillis();
        BitstampTicker response = client.target("https://www.bitstamp.net").path("api/ticker/")
                .request(MediaType.APPLICATION_JSON).get(BitstampTicker.class);
        PERF_LOGGER.info("Ticker retrieved from Bitstamp for currency USD in {} ms.",
                System.currentTimeMillis() - start);

        if (response != null) {
            result.setCurrencyCode("USD");
            result.setRefreshTime(new Date());
            result.setBuy(Float.parseFloat(response.getBid()));
            result.setHigh(Float.parseFloat(response.getHigh()));
            result.setLast(Float.parseFloat(response.getLast()));
            result.setLow(Float.parseFloat(response.getLow()));
            result.setSell(Float.parseFloat(response.getAsk()));
            result.setVolume(Float.parseFloat(response.getVolume()));
        } else {
            LOGGER.warn("Failed to retrieve the Bitstamp ticker for currency USD with no reason.",
                    currencyCode);
        }
    } catch (Exception e) {
        LOGGER.error("Failed to retrieve the Bitstamp ticker for currency USD.", currencyCode, e);
    }
    return result;
}

From source file:com.tom.deleteme.PrintAnnotations.java

/**
 * Prints all Annotations of a specified Type to a PrintStream.
 * /*www . j a v a  2  s. co  m*/
 * @param aCAS
 *          the CAS containing the FeatureStructures to print
 * @param aAnnotType
 *          the Type of Annotation to be printed
 * @param aOut
 *          the PrintStream to which output will be written
 */

public static void printAnnotatedText(FeatureStructure aFS, CAS aCAS, int aNestingLevel, PrintStream aOut,
        JSONObject json) {
    String annotationKey = aFS.getType().getName();
    if (json.get(annotationKey) == null) {
        if (!annotationKey.equals(tcasAnnotationKey)) {
            if (aFS instanceof AnnotationFS) {
                AnnotationFS annot = (AnnotationFS) aFS;
                String coveredText = annot.getCoveredText();
                if (annotationKey.equals(WorkExperienceKey)) {
                    coveredText = stringCleanUp(coveredText, "([\\d]{1,})?.?[\\d]{1,}");
                }
                if (annotationKey.equals(PinCodeKey)) {
                    coveredText = stringCleanUp(coveredText, "[\\d]{6}");
                }
                if (coveredText instanceof String) {
                    coveredText = processString(coveredText);
                }
                if (annotationKey.equals(WorkExperienceKey)) {
                    json.put(aFS.getType().getName(), Float.parseFloat(coveredText));
                } else {
                    json.put(annotationKey, coveredText);
                }
            }
        }
    } else if ((aFS.getType().getName()).equals(OtherNamedTagsKey)) {
        if (aFS instanceof AnnotationFS) {
            AnnotationFS annot = (AnnotationFS) aFS;
            String coveredText = annot.getCoveredText();
            coveredText = processString(coveredText);
            appendOtherNamedTags(json, coveredText);
        }
    }
}

From source file:dev.maisentito.suca.commands.AdminCommandHandler.java

@Override
public void handleCommand(MessageEvent event, String[] args) throws Throwable {
    if ((!Main.config.verifyOwner || event.getUser().isVerified())
            && event.getUser().getNick().equals(getStringGlobal(Main.GLOBAL_OWNER, ""))) {
        if (args.length < 2) {
            if (args.length == 1) {
                if (getGlobals().has(args[0], Object.class)) {
                    event.respond(/*from  w w w  .  j  av  a  2 s .c  o m*/
                            String.format("!admin: %s = %s", args[0], getGlobals().get(args[0]).toString()));
                } else {
                    event.respond(String.format("!admin: %s = null", args[0]));
                }
                return;
            } else {
                event.respond("!admin: not enough arguments");
                return;
            }
        } else if (args[1].length() < 3) {
            event.respond("!admin: invalid value");
            return;
        }

        String key = args[0];
        String full = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), ' ');
        Object value;

        switch (args[1].charAt(0)) {
        case 'c':
            value = args[1].charAt(2);
            break;
        case 'b':
            value = Byte.parseByte(args[1].substring(2));
            break;
        case 's':
            value = Short.parseShort(args[1].substring(2));
            break;
        case 'i':
            value = Integer.parseInt(args[1].substring(2));
            break;
        case 'l':
            value = Long.parseLong(args[1].substring(2));
            break;
        case 'f':
            value = Float.parseFloat(args[1].substring(2));
            break;
        case 'd':
            value = Double.parseDouble(args[1].substring(2));
            break;
        case 'z':
            value = Boolean.parseBoolean(args[1].substring(2));
            break;
        case 'a':
            value = full.substring(2);
            break;
        default:
            event.respond("!admin: invalid type");
            return;
        }

        getGlobals().put(key, value);
        event.respond("success");

    } else {
        event.respond("nope");
    }
}

From source file:edu.csudh.goTorosBank.WithdrawServlet.java

/**
 * TODO: Finish filling this out..../* w  ww  .  j a va2 s  . c o m*/
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException 
 */
@Override
@SuppressWarnings("unchecked") //need this to suppress warnings for our json.put
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    getServletContext().log("goGet () called");

    JSONObject returnJSON = new JSONObject();
    response.setContentType("application/json");

    HttpSession userSession = request.getSession();
    String username = (String) userSession.getAttribute("username");

    try {
        DatabaseInterface database = new DatabaseInterface();
        User myUser = database.getUser(username);
        if (request.getParameter("accountID") == null || request.getParameter("amount") == null) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Not valid arguments!");
            //response.getWriter().write(returnJSON.toJSONString());
            return;
        }
        int accountID = Integer.parseInt(request.getParameter("accountID"));
        float amount = Float.parseFloat(request.getParameter("amount"));
        Account accountFrom = myUser.getUserAccount(accountID);
        String personGettingPaid = request.getParameter("personGettingPaid");
        String billType = request.getParameter("billType");
        String memo = request.getParameter("memo");

        //Checks if user has selected an account
        if (myUser.getUserAccounts().size() == 0) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "No account to withdraw from");
        }

        //checks if user has sufficient funds
        else if (0 > (accountFrom.getAccountBalance() - amount)) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Insufficient funds in account" + accountFrom.getAccountNumber());
        }
        //checks that user withdraws in amounts of 20
        else if (amount % 20 != 0) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Must withdraw in amounts of 20");
        }
        //checks that uer doesn't withdraw more than $500.00
        else if (amount > 500) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "Withdraw amount cannot exceed $500.00");
        } else if (personGettingPaid == null) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "There is no person getting payed");
        } else if (billType == null) {
            returnJSON.put("successfulWithdraw", false);
            returnJSON.put("message", "There is no bill description");
        }
        //creates check for user and makes changes to the database...
        else {

            //response.setContentType("image/jpeg");
            File blueCheck = new File("blank-blue-check");
            String pathToWeb = getServletContext().getRealPath("/" + blueCheck);
            //File blueCheck = new File(pathToWeb + "blank-blue-check.jpg");
            returnJSON.put("pathToWeb", pathToWeb);

            String fullpath = writeIntoCheck(pathToWeb, username, Float.toString(amount), "AMOUNT IN WORDS",
                    "DATE", personGettingPaid, "BULLSHIT");
            String[] fullpathSplit = fullpath.split("/");
            String filename = fullpathSplit[fullpathSplit.length - 1];
            database.withdraw(accountID, amount, username);
            returnJSON.put("filename", filename);
            returnJSON.put("successfulWithdraw", true);
            returnJSON.put("message", "Successfully withdrew $" + amount + " from account " + accountID);
        }
    } catch (SQLException s) {
        returnJSON.put("errorMessage", "Sorry we have a SQLException");
        returnJSON.put("errorMessage2", s);
    } catch (ClassNotFoundException cl) {
        returnJSON.put("errorMessage", "Sorry we have a ClassNotFoundException");
        returnJSON.put("errorMessage2", cl);
    } catch (ParseException p) {
        returnJSON.put("successfulWithdraw", false);
        returnJSON.put("message", "ParseException: " + p.getMessage());
    }
    /*added new case, where parseInt finds nothing*/
    catch (NumberFormatException e) {
        returnJSON.put("successfulWithdraw", false);
        returnJSON.put("message", "NumberFormatException " + e.getMessage());
    }
    response.getWriter().write(returnJSON.toJSONString());
}

From source file:evaluation.loadGenerator.mixPacketLevelTraffic.MPL_FS_Poisson.java

public MPL_FS_Poisson(MPL_FixedScheduleLoadGenerator owner) {
    this.settings = owner.getSettings();
    this.experimentStart = owner.getScheduler().now() + TimeUnit.SECONDS.toNanos(2);
    this.startOfPeriod = experimentStart;
    int numberOfClients = settings.getPropertyAsInt("MPL-POISSON-NUMBER_OF_CLIENTS");

    String str_avgSendsPerPulse = settings.getProperty("MPL-POISSON-AVERAGE_PACKETS_PER_PULSE");
    if (RandomVariable.isRandomVariable(str_avgSendsPerPulse)) {
        this.AVG_SENDS_PER_PERIOD = RandomVariable.createRandomVariable(str_avgSendsPerPulse);
    } else {// w  w w  . j  a v a 2  s.  c  o m
        float float_avgSendsPerPulse = Float.parseFloat(str_avgSendsPerPulse);
        float_avgSendsPerPulse = float_avgSendsPerPulse * (float) numberOfClients;
        if (float_avgSendsPerPulse < 1f)
            this.AVG_SENDS_PER_PERIOD = new FakeRandom(1);
        else
            this.AVG_SENDS_PER_PERIOD = new FakeRandom(Math.round(float_avgSendsPerPulse));
    }
    this.PULSE_LENGTH = (long) (settings.getPropertyAsFloat("MPL-POISSON-PULSE_LENGTH") * 1000000000f);
    this.random = new SecureRandom();
    this.randomDataImpl = new RandomDataImpl();
    this.randomDataImpl.reSeed(this.random.nextLong());
    System.out.println("LOAD_GENERATOR: start at " + experimentStart);

    // create client
    owner.getLoadGenerator().commandLineParameters.gMixTool = ToolName.CLIENT;
    this.client = new AnonNode(owner.getLoadGenerator().commandLineParameters);
    int dstPort = settings.getPropertyAsInt("SERVICE_PORT1");
    this.scheduleTarget = new MPL_BasicWriter(this, client.IS_DUPLEX, dstPort);
    // determine number of clients and lines; create ClientWrapper objects etc
    this.clientsArray = new MPL_ClientWrapper[numberOfClients];
    CommunicationDirection cm = client.IS_DUPLEX ? CommunicationDirection.DUPLEX
            : CommunicationDirection.SIMPLEX_SENDER;
    for (int i = 0; i < numberOfClients; i++) {
        clientsArray[i] = new MPL_ClientWrapper(i);
        clientsArray[i].socket = client.createDatagramSocket(cm, true, true,
                client.ROUTING_MODE != RoutingMode.CASCADE);
    }
    if (client.IS_DUPLEX) {
        this.replyReceiver = new MPL_ReplyReceiver(clientsArray, settings);
        //this.replyReceiver.registerObserver(this);
        this.replyReceiver.start();
    }
}