Showing posts with label Float. Show all posts
Showing posts with label Float. Show all posts

String.valueOf - How to Convert an Float to String

public static Float valueOf(float f)
Returns a Float instance representing the specified float value. If a new Float instance is not required, this method should generally be used in preference to the constructor Float(float), as this method is likely to yield significantly better space and time performance by caching frequently requested values. Parameters: f - a float value.Returns: a Float instance representing f.

1. In the MainActivity.java file, add a Toast which displays the value of String.valueOf(3.567f);

Toast.makeText(this, String.valueOf(3.567f), Toast.LENGTH_LONG).show(); 

2. Compile and run!
3. The display results will be (as a string): 3.567

Resources:
http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#valueOf(float)

How to Convert Float to Integer

To save a float variable to a integer variable, the float variable must be converted to an integer.

1. Set a Float Variable named myFloat to 3.8644f;

2. Set an Integer Variable named myInteger to (int) myFloat. This will save the value of myFloat to the integer variable named myInteger and convert it to an integer. 

How to Set a Float Variable


1. Declare a Float Variable named myFloat.

2. Add the below line to the onCreate method. This will set the float variable named myFloat to 3.8644f.

myFloat = 3.8644f;

3. Compile and run!

Resources:
http://developer.android.com/reference/java/lang/Float.html


How to Declare a Float Variable

The Float class wraps a value of the primitive type float in an object. An object of type Float contains a single field whose type is float.

Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float myFloat = 234.5f

1. In the MainActivity.java file, add the below to the onCreate method. This will create a Float variable named myFloat.

float myFloat; 

2. Compile and run!

Resources:
http://developer.android.com/reference/java/lang/Float.html
http://www.tutorialspoint.com/java/java_basic_datatypes.htm