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.seleniumtests.browserfactory.BrowserInfo.java

/**
 * /*from  w w w  .j  ava2 s.  c om*/
 * @param browser
 * @param version
 * @param path            path to browser executable
 * @param check            do we check if browser path exists or not. Should not be used outside of tests
 */
public BrowserInfo(BrowserType browser, String version, String path, boolean check) {
    this.browser = browser;
    this.path = path;

    if (path != null && check && !Paths.get(path).toFile().exists()) {
        throw new ConfigurationException(String.format("browser file %s does not exists", path));
    }

    try {
        Float.parseFloat(version);
        this.version = version;
    } catch (NumberFormatException e) {
        logger.warn(String.format("Cannot parse browser version %s for browser", version, browser));
        this.version = "0.0";
    }

    os = OSUtility.getCurrentPlatorm().toString().toLowerCase();
}

From source file:com.pixellostudio.qqdroid.BaseQuote.java

/** Called when the activity is first created. */
@Override/*w  w w  . ja va2s.c om*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setActionBarContentView(R.layout.show);

    getActionBar().setTitle(title);

    getActionBar().addItem(getActionBar().newActionBarItem(NormalActionBarItem.class)
            .setDrawable(R.drawable.seemore).setContentDescription("List"), R.id.actionbar_seemore);

    view = (ListView) findViewById(R.id.ListView);

    view.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.add(0, 1, 0, R.string.sharequote);
        }
    });

    adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1);
    adapter2 = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(BaseQuote.this);

            TextView txt = new TextView(this.getContext());
            txt.setTextSize(Float.parseFloat(pref.getString("policesize", "20")));
            txt.setText(Html.fromHtml(this.getItem(position)));

            if (pref.getString("design", "blackonwhite").equals("blackonwhite")) {
                txt.setTextColor(Color.BLACK);
                txt.setBackgroundColor(Color.WHITE);
                txt.setBackgroundDrawable(
                        this.getContext().getResources().getDrawable(R.drawable.quote_gradient_white));
            } else if (pref.getString("design", "blackonwhite").equals("whiteonblack")) {
                txt.setTextColor(Color.WHITE);
                txt.setBackgroundColor(Color.BLACK);
                txt.setBackgroundDrawable(
                        this.getContext().getResources().getDrawable(R.drawable.quote_gradient_black));
            }

            return txt;
        }

    };

    String[] liste = (String[]) getLastNonConfigurationInstance();

    if (liste != null && liste.length != 0) {
        for (int i = 0; i < liste.length; i++) {
            adapter.add(liste[i]);
            adapter2.add(liste[i]);
        }

        this.setTitle(name);
    } else {
        new LoadQuotes().execute();
    }

    view.setAdapter(adapter2);
}

From source file:Data.Player.java

public void sportingcharts(String input) {
    temp = input.split("\">");

    //div = Float.parseFloat(temp[5].substring(0, temp[5].indexOf("<")).replace(",", ""));
    toi = Float.parseFloat(temp[6].substring(0, temp[6].indexOf("<")));

    float div = toi * gp / 60;

    goals60 = round(goals / div, 3);/* w  w w.  j a v  a 2 s. c  om*/
    assists60 = round(assists / div, 3);
    points60 = round(points / div, 3);
    stp60 = round(stp / div, 3);
    esp60 = round(esp / div, 3);
    sog60 = round(sog / div, 3);
    hits60 = round(hits / div, 3);
    blocks60 = round(blocks / div, 3);
}

From source file:com.punyal.blackhole.core.net.rockbolt.RockboltClient.java

public RockboltClient(Ticket myTicket, final LWM2Mdevice device) {
    this.myTicket = myTicket;
    this.device = device;
    this.setDaemon(true);
    running = true;/*from  w ww.  ja  v  a 2  s.c o  m*/
    strainObserver = new CoapObserver(myTicket, device.getEndPoint(), COAP_RESOURCE_STRAIN) {

        @Override
        public void incomingData(CoapResponse response) {
            device.increaseMessageIn();
            if (!response.getResponseText().isEmpty()) {
                try {
                    device.incomingData(COAP_RESOURCE_STRAIN, response.getResponseText());
                    JSONObject json = Parsers.senml2json(response.getResponseText());
                    device.addStrainData(Integer.parseInt(json.get("strain").toString()));
                } catch (NullPointerException ex) {
                }
            }

        }

        @Override
        public void error() {
            System.out.println("Error Strain resource on " + device.getName());
        }
    };
    rmsObserver = new CoapObserver(myTicket, device.getEndPoint(), COAP_RESOURCE_RMS) {

        @Override
        public void incomingData(CoapResponse response) {
            device.increaseMessageIn();
            if (!response.getResponseText().isEmpty()) {
                try {
                    device.incomingData(COAP_RESOURCE_RMS, response.getResponseText());
                    JSONObject json = Parsers.senml2json(response.getResponseText());
                    device.addVibrationData(Float.parseFloat(json.get("X").toString()),
                            Float.parseFloat(json.get("Y").toString()),
                            Float.parseFloat(json.get("Z").toString()));
                } catch (NullPointerException ex) {
                }
            }
        }

        @Override
        public void error() {
            System.out.println("Error RMS resource on " + device.getName());
        }
    };

    batteryObserver = new CoapObserver(myTicket, device.getEndPoint(), COAP_RESOURCE_BATTERY) {

        @Override
        public void incomingData(CoapResponse response) {
            device.increaseMessageIn();
            if (!response.getResponseText().isEmpty()) {
                JSONObject json = Parsers.senml2json(response.getResponseText());
                if (json.get("Vbat") != null) {
                    int battery = Integer.parseInt(json.get("Vbat").toString());
                    device.setBatteryLevel(battery);
                }
            }
        }

        @Override
        public void error() {
            System.out.println("Error RMS resource on " + device.getName());
        }
    };
}

From source file:org.yamj.common.tools.PropertyTools.java

/**
 * Return the key property as a float/*from   w  w  w . j a  v  a2  s.co  m*/
 *
 * @param key
 * @param defaultValue
 * @return
 */
public static float getFloatProperty(String key, float defaultValue) {
    String property = PROPERTIES.getProperty(key);
    if (property != null) {
        try {
            return Float.parseFloat(property.trim());
        } catch (NumberFormatException nfe) {
        }
    }
    return defaultValue;
}

From source file:evaluation.loadGenerator.fixedSchedule.ALM_FS_Poisson.java

public ALM_FS_Poisson(AL_FixedScheduleLoadGenerator owner) {
    this.settings = owner.getSettings();
    this.experimentStart = owner.getScheduler().now() + TimeUnit.SECONDS.toNanos(2);
    this.startOfPeriod = experimentStart;
    int numberOfClients = settings.getPropertyAsInt("AL-POISSON-NUMBER_OF_CLIENTS");
    String str_avgSendsPerPulse = settings.getProperty("AL-POISSON-AVERAGE_SEND_OPERATIONS_PER_PULSE");
    if (RandomVariable.isRandomVariable(str_avgSendsPerPulse)) {
        this.AVG_SENDS_PER_PERIOD = RandomVariable.createRandomVariable(str_avgSendsPerPulse);
    } else {//from www  .ja 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));
    }
    String str_ReplyDelay = settings.getProperty("AL-POISSON-REPLY_DELAY");
    if (RandomVariable.isRandomVariable(str_ReplyDelay))
        this.REPLY_DELAY = RandomVariable.createRandomVariable(str_ReplyDelay);
    else
        this.REPLY_DELAY = new FakeRandom(Double.parseDouble(str_ReplyDelay));
    this.PULSE_LENGTH = (long) (settings.getPropertyAsFloat("AL-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);
    this.scheduleTarget = new ALRR_BasicWriter(this, client.IS_DUPLEX);
    // determine number of clients and lines; create ClientWrapper objects etc
    this.clientsArray = new ALRR_ClientWrapper[numberOfClients];
    CommunicationDirection cm = client.IS_DUPLEX ? CommunicationDirection.DUPLEX
            : CommunicationDirection.SIMPLEX_SENDER;
    int port = settings.getPropertyAsInt("SERVICE_PORT1");
    System.out.println("LOAD_GENERATOR: connecting clients...");
    for (int i = 0; i < numberOfClients; i++) {
        clientsArray[i] = new ALRR_ClientWrapper(i);
        clientsArray[i].socket = client.createStreamSocket(cm, client.ROUTING_MODE != RoutingMode.CASCADE);
        try {
            clientsArray[i].socket.connect(port);
            clientsArray[i].outputStream = new BufferedOutputStream(clientsArray[i].socket.getOutputStream());
            if (client.IS_DUPLEX)
                clientsArray[i].inputStream = clientsArray[i].socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String str_requestPayloadSize = settings.getProperty("AL-POISSON-REQUEST_PAYLOAD_SIZE");
    if (RandomVariable.isRandomVariable(str_requestPayloadSize)) {
        this.REQUEST_PAYLOAD_SIZE = RandomVariable.createRandomVariable(str_requestPayloadSize);
    } else {
        if (str_requestPayloadSize.equalsIgnoreCase("AUTO"))
            this.REQUEST_PAYLOAD_SIZE = new FakeRandom(clientsArray[0].socket.getMTU());
        else
            this.REQUEST_PAYLOAD_SIZE = new FakeRandom(Integer.parseInt(str_requestPayloadSize));
    }
    String str_replyPayloadSize = settings.getProperty("AL-POISSON-REPLY_PAYLOAD_SIZE");
    if (RandomVariable.isRandomVariable(str_replyPayloadSize)) {
        this.REPLY_PAYLOAD_SIZE = RandomVariable.createRandomVariable(str_replyPayloadSize);
    } else {
        if (str_replyPayloadSize.equalsIgnoreCase("AUTO"))
            this.REPLY_PAYLOAD_SIZE = new FakeRandom(clientsArray[0].socket.getMTU());
        else
            this.REPLY_PAYLOAD_SIZE = new FakeRandom(Integer.parseInt(str_replyPayloadSize));
    }
    if (client.IS_DUPLEX) {
        this.replyReceiver = new ALRR_ReplyReceiver(clientsArray, settings);
        //this.replyReceiver.registerObserver(this);
        this.replyReceiver.start();
    }
}

From source file:com.netflix.ice.processor.ReservationCapacityPoller.java

@Override
protected void poll() throws Exception {
    ProcessorConfig config = ProcessorConfig.getInstance();

    // read from s3 if not exists
    File file = new File(config.localDir, "reservation_capacity.txt");

    if (!file.exists()) {
        logger.info("downloading " + file + "...");
        AwsUtils.downloadFileIfNotExist(config.workS3BucketName, config.workS3BucketPrefix, file);
        logger.info("downloaded " + file);
    }//from w  w w  . j a v  a2  s.c  om

    // read from file
    Map<String, ReservedInstances> reservations = Maps.newTreeMap();
    if (file.exists()) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line;

            while ((line = reader.readLine()) != null) {
                String[] tokens = line.split(",");
                String accountId = tokens[0];
                String region = tokens[1];
                String reservationId = tokens[2];
                String zone = tokens[3];
                Long start = Long.parseLong(tokens[4]);
                long duration = Long.parseLong(tokens[5]);
                String instanceType = tokens[6];
                String productDescription = tokens[7];
                int instanceCount = Integer.parseInt(tokens[8]);
                String offeringType = tokens[9];
                String state = tokens[10];
                Long end = tokens.length > 11 ? Long.parseLong(tokens[11]) : null;
                float fixedPrice = tokens.length > 12 ? Float.parseFloat(tokens[12]) : 0;
                float usagePrice = tokens.length > 13 ? Float.parseFloat(tokens[13]) : 0;

                ReservedInstances reservation = new ReservedInstances().withAvailabilityZone(zone)
                        .withStart(new Date(start)).withDuration(duration).withInstanceType(instanceType)
                        .withProductDescription(productDescription).withInstanceCount(instanceCount)
                        .withOfferingType(offeringType).withState(state).withFixedPrice(fixedPrice)
                        .withUsagePrice(usagePrice);
                if (end != null)
                    reservation.setEnd(new Date(end));
                else
                    reservation.setEnd(new Date(start + duration * 1000));

                reservations.put(accountId + "," + region + "," + reservationId, reservation);
            }
        } catch (Exception e) {
            logger.error("error in reading " + file, e);
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (Exception e) {
                }
        }
    }
    logger.info("read " + reservations.size() + " reservations.");

    for (Account account : config.accountService.getReservationAccounts().keySet()) {
        try {
            AmazonEC2Client ec2Client;
            String assumeRole = config.accountService.getReservationAccessRoles().get(account);
            if (assumeRole != null) {
                String externalId = config.accountService.getReservationAccessExternalIds().get(account);
                final Credentials credentials = AwsUtils.getAssumedCredentials(account.id, assumeRole,
                        externalId);
                ec2Client = new AmazonEC2Client(new AWSSessionCredentials() {
                    public String getAWSAccessKeyId() {
                        return credentials.getAccessKeyId();
                    }

                    public String getAWSSecretKey() {
                        return credentials.getSecretAccessKey();
                    }

                    public String getSessionToken() {
                        return credentials.getSessionToken();
                    }
                });
            } else
                ec2Client = new AmazonEC2Client(AwsUtils.awsCredentialsProvider.getCredentials(),
                        AwsUtils.clientConfig);

            for (Region region : Region.getAllRegions()) {

                ec2Client.setEndpoint("ec2." + region.name + ".amazonaws.com");

                try {
                    DescribeReservedInstancesResult result = ec2Client.describeReservedInstances();
                    for (ReservedInstances reservation : result.getReservedInstances()) {
                        String key = account.id + "," + region.name + ","
                                + reservation.getReservedInstancesId();
                        reservations.put(key, reservation);
                        if (reservation.getEnd() == null)
                            reservation.setEnd(new Date(
                                    reservation.getStart().getTime() + reservation.getDuration() * 1000L));
                        if (reservation.getFixedPrice() == null)
                            reservation.setFixedPrice(0f);
                        if (reservation.getUsagePrice() == null)
                            reservation.setUsagePrice(0f);
                    }
                } catch (Exception e) {
                    logger.error("error in describeReservedInstances for " + region.name + " " + account.name,
                            e);
                }
            }

            ec2Client.shutdown();
        } catch (Exception e) {
            logger.error("Error in describeReservedInstances for " + account.name, e);
        }
    }

    config.reservationService.updateEc2Reservations(reservations);
    updatedConfig = true;

    // archive to disk
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(file));
        for (String key : reservations.keySet()) {
            ReservedInstances reservation = reservations.get(key);
            String[] line = new String[] { key, reservation.getAvailabilityZone(),
                    reservation.getStart().getTime() + "", reservation.getDuration().toString(),
                    reservation.getInstanceType(), reservation.getProductDescription(),
                    reservation.getInstanceCount().toString(), reservation.getOfferingType(),
                    reservation.getState(), reservation.getEnd().getTime() + "",
                    reservation.getFixedPrice() + "", reservation.getUsagePrice() + "", };
            writer.write(StringUtils.join(line, ","));
            writer.newLine();
        }
    } catch (Exception e) {
        logger.error("", e);
    } finally {
        if (writer != null)
            try {
                writer.close();
            } catch (Exception e) {
            }
    }
    logger.info("archived " + reservations.size() + " reservations.");

    // archive to s3
    logger.info("uploading " + file + "...");
    AwsUtils.upload(config.workS3BucketName, config.workS3BucketPrefix, config.localDir, file.getName());
    logger.info("uploaded " + file);
}

From source file:edu.uci.ics.asterix.optimizer.base.FuzzyUtils.java

public static float getSimThreshold(AqlMetadataProvider metadata) {
    float simThreshold = JACCARD_DEFAULT_SIM_THRESHOLD;
    String simThresholValue = metadata.getPropertyValue(SIM_THRESHOLD_PROP_NAME);
    if (simThresholValue != null) {
        simThreshold = Float.parseFloat(simThresholValue);
    }/*ww  w  .  j a v a2 s  . c om*/
    return simThreshold;
}

From source file:com.kotcrab.vis.editor.ui.scene.entityproperties.NumberInputField.java

private void changeFieldValue(float value) {
    try {/* w  w  w.  j  av a  2s  .  c om*/
        float fieldValue = Float.parseFloat(getText());
        fieldValue += value;

        int lastPos = getCursorPosition();
        setText(floatToString(fieldValue));
        NumberInputField.this.setCursorPosition(lastPos);
        fire(new ChangeEvent());
    } catch (NumberFormatException ex) {
    }
}

From source file:com.sk89q.commandbook.locations.FlatFileLocationsManager.java

public void load() throws IOException {
    FileInputStream input = null;
    Map<String, NamedLocation> locs = new HashMap<String, NamedLocation>();
    boolean needsSaved = false;

    if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
        if (!file.exists()) {
            file.createNewFile();// ww w  .ja v a 2  s . c o m
        }
    }

    try {
        input = new FileInputStream(file);
        InputStreamReader streamReader = new InputStreamReader(input, "utf-8");
        BufferedReader reader = new BufferedReader(streamReader);

        CSVReader csv = new CSVReader(reader);
        String[] line;
        while ((line = csv.readNext()) != null) {
            int lineLen = line.length;
            if (lineLen < 8) {
                logger().warning(type + " data file has an invalid line with < 8 fields");
            } else {
                try {
                    int i = 0;
                    String name = line[i++].trim().replace(" ", "");
                    String worldName = line[i++]; // Set to null if the world exists
                    String creator = line[i++];
                    double x = Double.parseDouble(line[i++]);
                    double y = Double.parseDouble(line[i++]);
                    double z = Double.parseDouble(line[i++]);
                    float pitch = Float.parseFloat(line[i++]);
                    float yaw = Float.parseFloat(line[i++]);

                    World world = CommandBook.server().getWorld(worldName);

                    if (world != null) {
                        // We shouldn't have this warp
                        if (castWorld != null && !castWorld.equals(world)) {
                            continue;
                        }
                    }

                    Location loc = new Location(world, x, y, z, yaw, pitch);
                    NamedLocation warp = new NamedLocation(name, loc);
                    warp.setWorldName(worldName);

                    try {
                        warp.setCreatorID(UUID.fromString(creator));
                    } catch (IllegalArgumentException ex) {
                        logger().finest("Converting " + type + " " + name + "'s owner record to UUID...");
                        UUID creatorID = UUIDUtil.convert(creator);
                        if (creatorID != null) {
                            warp.setCreatorID(creatorID);
                            needsSaved = true;
                            logger().finest("Success!");
                        } else {
                            warp.setCreatorName(creator);
                            logger().warning(type + " " + name + "'s owner could not be converted!");
                        }
                    }
                    if (world == null) {
                        getNestedList(unloadedLocations, worldName).add(warp);
                    } else {
                        locs.put(name.toLowerCase(), warp);
                    }
                } catch (IllegalArgumentException e) {
                    if (e instanceof NumberFormatException) {
                        logger().warning(type + " data file has an invalid line with an invalid UUID field");
                    } else {
                        logger().warning(
                                type + " data file has an invalid line with non-numeric numeric fields");
                    }
                }
            }
        }

        this.locations = locs;

        if (castWorld != null) {
            logger().info(locs.size() + " " + type + "(s) loaded for " + castWorld.getName());
        } else {
            logger().info(locs.size() + " " + type + "(s) loaded");
        }
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException ignore) {
            }
        }
    }
    if (needsSaved)
        save();
}