Showing posts with label Convert. Show all posts
Showing posts with label Convert. Show all posts

String.valueOf - How to Convert a Double to a String

public static String valueOf (int value) was added in API level 1
Converts the specified double to its string representation.
Parameters: value - the double.
Returns: the double converted to a string
(** I prefer to use String.valueOf over, Double.toString() **)

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

Toast.makeText(getBaseContext(), String.valueOf(1.11), Toast.LENGTH_LONG).show(); 

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

Resources:
http://stackoverflow.com/questions/3335737/integer-tostringint-i-vs-string-valueofint-i

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.