Example usage for java.lang Float toString

List of usage examples for java.lang Float toString

Introduction

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

Prototype

public static String toString(float f) 

Source Link

Document

Returns a string representation of the float argument.

Usage

From source file:ontopoly.conversion.ConversionUtils.java

private static String inferAndCreateSchema(TopicMap oldTopicMap, TopicMap newTopicMap, String tmname,
        TopicMapRepositoryIF repository) {

    boolean newtopicmap = (oldTopicMap != null);

    // create new topic map 
    TopicMapStoreIF store = newTopicMap.getTopicMapIF().getStore();
    try {/*from  w  w w  .  j a  va 2 s  .co m*/

        TopicMapStoreIF oldstore = null;
        LocatorIF oldbaseloc = null;
        if (newtopicmap) {

            // get old store
            oldstore = oldTopicMap.getTopicMapIF().getStore();
            oldbaseloc = oldstore.getBaseAddress();

        }

        // convert topic map
        TopicMapIF tm = store.getTopicMap();
        Collection<LocatorIF> reifier_subinds = new HashSet<LocatorIF>();

        LocatorIF versionTopicPSI = URILocator.create("http://psi.ontopia.net/ontology/ted-ontology-version");
        if (newtopicmap) {
            // get hold of old reifier
            TopicIF oreifier = oldstore.getTopicMap().getReifier();
            if (oreifier == null) {
                reifier_subinds = Collections.emptySet();
            } else {
                reifier_subinds = oreifier.getSubjectIdentifiers();
            }
            // merge in old topic map
            try {
                MergeUtils.mergeInto(store.getTopicMap(), oldstore.getTopicMap());
            } finally {
                oldstore.close();
            }
        } else {
            // import TED ontology
            TopicMapReferenceIF ontologyTopicMapReference = repository
                    .getReferenceByKey(OntopolyRepository.ONTOLOGY_TOPIC_MAP_ID);
            if (ontologyTopicMapReference == null)
                throw new OntopiaRuntimeException(
                        "Could not find ontology topic map '" + OntopolyRepository.ONTOLOGY_TOPIC_MAP_ID + "'");
            TopicMapStoreIF ontologyTopicMapStore = ontologyTopicMapReference.createStore(true);
            try {
                MergeUtils.mergeInto(tm, ontologyTopicMapStore.getTopicMap());
            } finally {
                ontologyTopicMapStore.close();
            }

            // reify topic map
            TopicMapBuilderIF tmbuilder = tm.getBuilder();
            TopicIF reifier = tm.getReifier();
            if (reifier == null) {
                reifier = tmbuilder.makeTopic();
                tm.setReifier(reifier);
                tmbuilder.makeTopicName(reifier, tmname);
                TopicIF versionTopic = tm.getTopicBySubjectIdentifier(versionTopicPSI);
                tmbuilder.makeOccurrence(reifier, versionTopic,
                        Float.toString(OntopolyApplication.CURRENT_VERSION_NUMBER));
            }
        }

        // copy old reifier reify topic map if not already done
        TopicIF nreifier = tm.getReifier();
        TopicIF oreifier = null;
        Iterator<LocatorIF> iiter = reifier_subinds.iterator();
        while (iiter.hasNext()) {
            LocatorIF reifier_subind = iiter.next();
            oreifier = tm.getTopicBySubjectIdentifier(reifier_subind);
            if (oreifier != null)
                break;
        }
        TopicMapBuilderIF tmbuilder = tm.getBuilder();
        if (nreifier == null) {
            if (oreifier != null) {
                nreifier = oreifier;
            } else {
                nreifier = tmbuilder.makeTopic();
                tm.setReifier(nreifier);
            }

        } else {
            if (oreifier != null && !Objects.equals(oreifier, nreifier))
                MergeUtils.mergeInto(nreifier, oreifier);
        }
        // make topic map reifier and instance of on:topic-map
        nreifier.addType(topicByPSI(psibase.resolveAbsolute("topic-map"), tm));

        // replace reifier names with new one
        if (newtopicmap) {
            Object[] nrnames = nreifier.getTopicNames().toArray();
            for (int i = 0; i < nrnames.length; i++) {
                TopicNameIF tn = (TopicNameIF) nrnames[i];
                tn.remove();
            }
            // String tmname = oldTopicMap.getName();1
            tmbuilder.makeTopicName(nreifier, tmname);
        }
        // Check ontology version:
        TopicIF versionTopic = tm.getTopicBySubjectIdentifier(versionTopicPSI);
        String versionNumber = Float.toString(OntopolyApplication.CURRENT_VERSION_NUMBER);
        OccurrenceIF versionOcc = getOccurrenceOfType(nreifier, versionTopic);
        if (versionOcc == null)
            // create new ontology version occurrence
            tmbuilder.makeOccurrence(nreifier, versionTopic, versionNumber);
        else
            // Update ontology version value
            versionOcc.setValue(versionNumber);

        // infer TED schema
        inferAndCreateSchema(tm, nreifier);

        // run duplicate suppression
        DuplicateSuppressionUtils.removeDuplicates(tm);

        TopicMapReferenceIF ref = store.getReference();
        if (ref instanceof XTMTopicMapReference) {
            // use old base address
            LocatorIF newbaseloc = store.getBaseAddress();
            if (oldbaseloc != null)
                ((AbstractTopicMapStore) store).setBaseAddress(oldbaseloc);

            // save topic map with TED ontology
            ((XTMTopicMapReference) ref).save();

            // revert to new base address
            if (oldbaseloc != null)
                ((AbstractTopicMapStore) store).setBaseAddress(newbaseloc);

            // close reference
            ref.close();
        }

        // commit changes to topic map
        store.commit();

    } catch (Throwable e) {
        if (store != null)
            store.abort();
        throw new OntopiaRuntimeException(e);
    } finally {
        if (store != null)
            store.close();
    }

    // refresh repository, so that new reference is visible
    repository.refresh();

    return newTopicMap.getId();
}

From source file:SignificantFigures.java

/**
 * Create a SignificantFigures object from a float.
 *
 * @param number a 32 bit floating point.
 *
 * @since ostermillerutils 1.00.00// w  w  w. ja v a  2  s  .  c om
 */
public SignificantFigures(float number) {
    original = Float.toString(number);
    try {
        parse(original);
    } catch (NumberFormatException nfe) {
        digits = null;
    }
}

From source file:org.ecocean.ImageProcessor.java

public void run() {
    //        status = Status.INIT;

    if (StringUtils.isBlank(this.command)) {
        log.warn("Can't run processor due to empty command");
        return;/*from   ww  w .jav a2 s.c  o m*/
    }

    if (StringUtils.isBlank(this.imageSourcePath)) {
        log.warn("Can't run processor due to empty source path");
        return;
    }

    if (StringUtils.isBlank(this.imageTargetPath)) {
        log.warn("Can't run processor due to empty target path");
        return;
    }

    String comment = CommonConfiguration.getProperty("imageComment", this.context);
    if (comment == null)
        comment = "%year All rights reserved. | wildbook.org";
    String cname = ContextConfiguration.getNameForContext(this.context);
    if (cname != null)
        comment += " | " + cname;
    String maId = "unknown";
    String rotation = "";
    if (this.parentMA != null) {
        if (this.parentMA.getUUID() != null) {
            maId = this.parentMA.getUUID();
            comment += " | parent " + maId;
        } else {
            maId = this.parentMA.setHashCode();
            comment += " | parent hash " + maId; //a stretch, but maybe should never happen?
        }
        if (this.parentMA.hasLabel("rotate90")) {
            rotation = "-flip -transpose";
        } else if (this.parentMA.hasLabel("rotate180")) {
            rotation = "-flip -flop";
        } else if (this.parentMA.hasLabel("rotate270")) {
            rotation = "-flip -transverse";
        }
    }
    comment += " | v" + Long.toString(System.currentTimeMillis());
    try {
        InetAddress ip = InetAddress.getLocalHost();
        comment += ":" + ip.toString() + ":" + ip.getHostName();
    } catch (UnknownHostException e) {
    }

    int year = Calendar.getInstance().get(Calendar.YEAR);
    comment = comment.replaceAll("%year", Integer.toString(year));
    //TODO should we handle ' better? -- this also assumes command uses '%comment' quoting  :/
    comment = comment.replaceAll("'", "");

    String fullCommand;
    fullCommand = this.command.replaceAll("%width", Integer.toString(this.width))
            .replaceAll("%height", Integer.toString(this.height))
            //.replaceAll("%imagesource", this.imageSourcePath)
            //.replaceAll("%imagetarget", this.imageTargetPath)
            .replaceAll("%maId", maId).replaceAll("%additional", rotation).replaceAll("%arg", this.arg);

    //walk thru transform array and replace "tN" with transform[N]
    if (this.transform.length > 0) {
        for (int i = 0; i < this.transform.length; i++) {
            fullCommand = fullCommand.replaceAll("%t" + Integer.toString(i), Float.toString(this.transform[i]));
        }
    }

    String[] command = fullCommand.split("\\s+");

    //we have to do this *after* the split-on-space cuz files may have spaces!
    for (int i = 0; i < command.length; i++) {
        if (command[i].equals("%imagesource"))
            command[i] = this.imageSourcePath;
        if (command[i].equals("%imagetarget"))
            command[i] = this.imageTargetPath;
        //note this assumes comment stands alone. :/
        if (command[i].equals("%comment"))
            command[i] = comment;
        System.out.println("COMMAND[" + i + "] = (" + command[i] + ")");
    }
    //System.out.println("done run()");
    //System.out.println("command = " + Arrays.asList(command).toString());

    ProcessBuilder pb = new ProcessBuilder();
    pb.command(command);
    /*
            Map<String, String> env = pb.environment();
            env.put("LD_LIBRARY_PATH", "/home/jon/opencv2.4.7");
    */
    //System.out.println("before!");

    try {
        Process proc = pb.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String line;
        while ((line = stdInput.readLine()) != null) {
            System.out.println(">>>> " + line);
        }
        while ((line = stdError.readLine()) != null) {
            System.out.println("!!!! " + line);
        }
        proc.waitFor();
        System.out.println("DONE?????");
        ////int returnCode = p.exitValue();
    } catch (Exception ioe) {
        log.error("Trouble running processor [" + command + "]", ioe);
    }
    System.out.println("RETURN");
}

From source file:com.magnet.android.mms.request.GenericResponseParserPrimitiveTest.java

@SmallTest
public void testNumberResponse() throws MobileException, JSONException {
    GenericResponseParser<Integer> parser = new GenericResponseParser<Integer>(Integer.class);
    String response = Integer.toString(Integer.MIN_VALUE);

    Integer result = (Integer) parser.parseResponse(response.toString().getBytes());
    assertEquals(Integer.MIN_VALUE, result.intValue());

    Object nullresult = parser.parseResponse((byte[]) null);
    assertEquals(null, nullresult);/*from ww  w.j  av a 2s .c om*/

    long longvalue = new Random().nextLong();
    GenericResponseParser<Long> lparser = new GenericResponseParser<Long>(Long.class);
    long longresult = (Long) lparser.parseResponse(Long.toString(longvalue).getBytes());
    assertEquals(longvalue, longresult);

    short shortvalue = Short.MAX_VALUE;
    GenericResponseParser<Short> sparser = new GenericResponseParser<Short>(short.class);
    short shortresult = (Short) sparser.parseResponse(Short.toString(shortvalue).getBytes());
    assertEquals(shortvalue, shortresult);

    float floatvalue = new Random().nextFloat();
    GenericResponseParser<Float> fparser = new GenericResponseParser<Float>(Float.class);
    float floatresult = (Float) fparser.parseResponse(Float.toString(floatvalue).getBytes());
    assertEquals(String.valueOf(floatvalue), String.valueOf(floatresult));
    // use string as the value of the float

    double doublevalue = new Random().nextDouble();
    GenericResponseParser<Double> dparser = new GenericResponseParser<Double>(double.class);
    Double doubleresult = (Double) dparser.parseResponse(Double.toString(doublevalue).getBytes());
    assertEquals(String.valueOf(doublevalue), String.valueOf(doubleresult));

    byte bytevalue = Byte.MIN_VALUE + 10;
    GenericResponseParser<Byte> bparser = new GenericResponseParser<Byte>(Byte.class);
    Byte byteresult = (Byte) bparser.parseResponse(Byte.toString(bytevalue).getBytes());
    assertEquals(bytevalue, byteresult.byteValue());

}

From source file:org.energy_home.jemma.internal.ah.eh.esp.ESPConfiguration.java

public static void setConfigParameters(ESPConfigParameters configParameters) throws ESPException {
    if (configParameters == null) {
        if (f.exists())
            f.delete();/*from   w  ww.j ava 2s.  co  m*/
        configProperties = new Properties();
    } else {
        configProperties.setProperty(CONTRACTUAL_POWER_THRESHOLD_PROPERTY_NAME,
                Float.toString(configParameters.getContractualPowerThreshold()));
        configProperties.setProperty(PEAK_PRODUCED_POWER_PROPERTY_NAME,
                Float.toString(configParameters.getPeakProducedPower()));
        saveProperties();
    }
}

From source file:blue.soundObject.tracker.Column.java

public String getIncrementValue(String val) {
    String retVal = null;//from w w  w .j  ava2  s .  c om

    switch (type) {
    case TYPE_PCH:
        float baseTen = ScoreUtilities.getBaseTen(val);

        baseTen += 1.0f;

        int octave = (int) (baseTen / 12);
        float strPch = (baseTen % 12) / 100;

        retVal = Float.toString(octave + strPch);

        if (retVal.endsWith(".0") || retVal.endsWith(".1")) {
            retVal = retVal + "0";
        }

        break;
    case TYPE_BLUE_PCH:
        String[] parts = val.split("\\.");

        int scaleDegrees = getScale().getNumScaleDegrees();

        int iBaseTen = Integer.parseInt(parts[0]) * scaleDegrees;
        iBaseTen += Integer.parseInt(parts[1]);

        iBaseTen += 1;

        int iOctave = iBaseTen / scaleDegrees;
        int iScaleDegree = iBaseTen % scaleDegrees;

        retVal = iOctave + "." + iScaleDegree;

        break;
    case TYPE_NUM:

        double dNumVal = Double.parseDouble(val);

        dNumVal += 1;

        if (usingRange && dNumVal > rangeMax) {
            dNumVal = rangeMax;
        }

        if (restrictedToInteger) {
            retVal = Integer.toString((int) dNumVal);
        } else {
            retVal = Double.toString(dNumVal);
        }
        break;
    case TYPE_MIDI:

        int midiVal = Integer.parseInt(val) + 1;

        if (midiVal > 127) {
            return null;
        }

        retVal = Integer.toString(midiVal);
        break;
    case TYPE_STR:
        retVal = null;
        break;
    }

    return retVal;
}

From source file:org.apache.hadoop.mapred.TestMapCollection.java

private static void runTest(String name, int keylen, int vallen, int records, int ioSortMB, float recPer,
        float spillPer, boolean pedantic) throws Exception {
    JobConf conf = new JobConf(new Configuration(), SpillMapper.class);

    conf.setInt("io.sort.mb", ioSortMB);
    conf.set("io.sort.record.percent", Float.toString(recPer));
    conf.set("io.sort.spill.percent", Float.toString(spillPer));

    conf.setInt("test.keywritable.length", keylen);
    conf.setInt("test.valwritable.length", vallen);
    conf.setInt("test.spillmap.records", records);
    conf.setBoolean("test.pedantic.verification", pedantic);

    conf.setNumMapTasks(1);/*from  w  w w.  j av a2 s .  c o  m*/
    conf.setNumReduceTasks(1);
    conf.setInputFormat(FakeIF.class);
    conf.setOutputFormat(NullOutputFormat.class);
    conf.setMapperClass(SpillMapper.class);
    conf.setReducerClass(SpillReducer.class);
    conf.setMapOutputKeyClass(KeyWritable.class);
    conf.setMapOutputValueClass(ValWritable.class);

    LOG.info("Running " + name);
    JobClient.runJob(conf);
}

From source file:org.alarmapp.web.HttpWebClient.java

public void addAlarmStatusPosition(AuthToken authToken, WayPoint position) throws WebException {
    HashMap<String, String> data = new HashMap<String, String>();

    LogEx.verbose("Date string is" + DateUtil.isoFormat(position.getMeasureDateTime()));

    data.put("date", DateUtil.isoFormat(position.getMeasureDateTime()));
    data.put("lat", Float.toString(position.getPosition().getLatitude()));
    data.put("lon", Float.toString(position.getPosition().getLongitude()));
    data.put("direction", Float.toString(position.getDirection()));
    data.put("speed", Float.toString(position.getSpeed()));
    data.put("precision", Float.toString(position.getPrecision()));
    data.put("source", position.getMeasurementMethod().toString());

    String response = HttpUtil.request(
            url("web_service/alarm_notification/" + position.getOperationId() + "/add_position/"), data,
            createAuthHeader(authToken));
    LogEx.verbose("Set alarm state returned " + response);
}

From source file:de.unistuttgart.ipvs.pmp.infoapp.webservice.properties.DeviceProperties.java

@Override
public void commit() throws InternalDatabaseException, InvalidParameterException, IOException {
    try {/*from  w  w w . j ava 2s. c om*/
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("manufacturer", this.deviceOem.manufacturer));
        params.add(new BasicNameValuePair("apiLevel", Byte.toString(this.api)));
        params.add(new BasicNameValuePair("kernel", this.kernel));
        params.add(new BasicNameValuePair("model", this.deviceOem.model));
        params.add(new BasicNameValuePair("ui", this.deviceOem.ui));
        params.add(new BasicNameValuePair("displayResX", Short.toString(this.display.x)));
        params.add(new BasicNameValuePair("displayResY", Short.toString(this.display.y)));
        params.add(new BasicNameValuePair("cpuFrequency", Short.toString(this.cpu)));
        params.add(new BasicNameValuePair("memoryInternal", Short.toString(this.memoryInternal.total)));
        params.add(new BasicNameValuePair("memoryInternalFree", Short.toString(this.memoryInternal.free)));
        params.add(new BasicNameValuePair("memoryExternal", Short.toString(this.memoryExternal.total)));
        params.add(new BasicNameValuePair("memoryExternalFree", Short.toString(this.memoryExternal.free)));
        params.add(new BasicNameValuePair("cameraResolution", Float.toString(this.cameraRes)));

        StringBuilder sensorsSb = new StringBuilder();
        boolean first = true;
        for (String sensor : this.sensors) {
            if (first) {
                first = false;
            } else {
                sensorsSb.append(",");
            }
            sensorsSb.append(sensor);
        }
        params.add(new BasicNameValuePair("sensors", sensorsSb.toString()));

        params.add(new BasicNameValuePair("runtime", Float.toString(this.runtime)));

        super.service.requestPostService("update_device.php", params);
    } catch (JSONException e) {
        throw new IOException("Server returned no valid JSON object: " + e);
    }
}

From source file:gcm.play.android.samples.com.gcmquickstart.MainFragment.java

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {

    fileMaker = new FileMaker();

    mTextureView = (TextureView) view.findViewById(R.id.texture);
    mIntervalToRecordText = (EditText) view.findViewById(R.id.intervalToRecord);
    mLengthToRecordText = (EditText) view.findViewById(R.id.secondToRecord);
    mNumberOfRecordingsText = (EditText) view.findViewById(R.id.numRecordingsToMake);

    mButtonVideo = (Button) view.findViewById(R.id.video);
    mButtonAutoVideo = (Button) view.findViewById(R.id.video_repeat);

    mButtonAutoVideo.setOnClickListener(this);
    mButtonVideo.setOnClickListener(this);

    focusValueText = (TextView) view.findViewById(R.id.focusValue);
    mSeekBar = (SeekBar) view.findViewById(R.id.seekBar);
    mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override//from  ww  w . ja va 2s  .  c o m
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            focusValueText.setText(String.format("%d > %d", i, mLastSentFocusValue));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mLastSentFocusValue = seekBar.getProgress();
            focusValueText.setText(String.format("%d -> %d", seekBar.getProgress(), mLastSentFocusValue));

            new SendMessageTask(getContext()).execute(MainFragment.UPDATE_FOCUS_MESSAGE, "-1",
                    Float.toString(seekBar.getProgress()));
        }
    });

    mRepeatRecordingHandler = new Handler();

    // Enable when a connection to the server has been made.
    mButtonVideo.setEnabled(false);
    mButtonAutoVideo.setEnabled(false);

    // Set defaults for these.
    mIntervalToRecordText.setText(Double.toString(DEFAULT_RECORD_INTERVAL));
    mLengthToRecordText.setText(Double.toString(DEFAULT_RECORD_LENGTH));
    mNumberOfRecordingsText.setText(Integer.toString(DEFAULT_TIMES_TO_RECORD));

    //// FOR COMMUNICATION
    // Registering BroadcastReceiver

    mRegistrationProgressBar = (ProgressBar) view.findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                mInformationTextView.setText(getString(R.string.gcm_send_message));
                mButtonVideo.setEnabled(true);
                mButtonAutoVideo.setEnabled(true);
            } else {
                mInformationTextView.setText(getString(R.string.token_error_message));
            }
        }
    };
    mTogglePlaybackReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("dei", "Message received intent HIT");

            if (intent.getExtras().get("message").equals(START_RECORDING_MESSAGE)) {
                // Start recording.
                toggleVideoRecording(true, intent.getExtras().getInt("id"));
            } else {
                toggleVideoRecording(false, intent.getExtras().getInt("id"));
            }
        }
    };

    mReconnectBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // No longer allow recording until connection is reestablished.
            mButtonVideo.setEnabled(false);
            mButtonAutoVideo.setEnabled(false);
            mInformationTextView.setText("Record failed. Trying to reconnect to server.");

            // Try reestablishing connection.
            intent = new Intent(MainFragment.this.getActivity(), RegistrationIntentService.class);
            MainFragment.this.getActivity().startService(intent);
        }
    };

    mInformationTextView = (TextView) view.findViewById(R.id.informationTextView);
    mNumRecordingsTextView = (TextView) view.findViewById(R.id.numRecordingsTextView);

    registerReceiver();

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this.getActivity(), RegistrationIntentService.class);
        this.getActivity().startService(intent);
    }
}