float and double are two
data type which is used to store floating point values in Java and we often
need to convert String to float in Java and sometime even a Float object or float primitive
to String. One thing, which is worth remembering about floating point numbers in
Java is that they are approximate values, a float value 100.1f may hold
actual value as 100.099998, which will be clear, when we
seen examples of converting float to String and
vice-versa. By the way, It's easy to parse
String to float and vice-versa, as rich Java API provides several ways of
doing it. If you already familiar with converting
String to int or may be String
to double in Java, then you can extend same techniques and method to parse
float String values. key methods like valueOf() and parseInt(), which is
used to parse String to float are
overloaded for most primitive data types. If you are particularly interested on
rounding of float values, you can use RoundingMode and BigDecimal class, as
float and double are always approximate values and comparing two float variable
of same values may not always return true, that's why it's advised, not
to use float for monetary calculation. In this Java tutorial, we will first
see examples of parsing String to float in Java and later converting float to
String objects. Remember, we will use float and Float, a wrapper
class corresponding to float primitive, interchangeably because by using Java
1.5 autoboxing feature, they are automatically converted to each other,
without any Java code. For those, who are still in Java 1.4 or lower version,
then can use Float.floatValue() to convert Float wrapper
object to float primitive.
3 ways to parse String to float in Java
There are mainly three ways to convert String to float value in Java, by
using Float.valueOf(), Float.parseFloat() method and
by using constructor
of Float class, which accepts a String. All these methods throws NumberFormatException if float
value is illegal or not parsable. For example trying to convert a String "#200.2" will throw
Exception in thread "main" java.lang.NumberFormatException: For
input string: "#200.2". By the way it's legal to pass suffix "f" or "F" along with
floating point number e.g. "200.2F" will not
throw this error. Similarly, you can
also use same technique to parse any negative floating point number String to float in Java,
minus sign (-) is permitted in float String. You can use
code snippets given in example section
to parse String to float in Java. One thing, which is worth remembering,
while dealing with String and float is that,
comparing them in String
format and as float values may return different result. As shown in
following example
float f1 = 414.23f;
float f2 = Float.valueOf("414.23f");
String s1 = "414.23f";
String s2 = String.valueOf(f1);
boolean result1 =
(f1 == f2);
boolean result2 =
s1.equals(s2);
System.out.printf("Comparing
floating point numbers %f and %f as float"
+ " returns %b %n", f1,
f2, result1);
System.out.printf("Comparing
floating point numbers %s and %s as String"
+ " returns %b %n", s1,
s2, result2);
Output:
Comparing floating point numbers 414.230011 and 414.230011
as float returns true
Comparing floating point numbers 414.23f and 414.23
as String returns false
The reason, we get false is because of "f" suffix
present in String, which is not very uncommon.
Also, it's good idea to remove whitespaces from String before converting them to float in Java.
3 example to convert float to String in Java
Now we know how to parse String to float in Java, it's time to explore
second part, converting a float to String.
This is even easier than first part. One of the quickest way to get an String object
from float value is to concatenate it with an empty
String e.g. "" + float, this will give you String object for
all your practical purpose. Apart from this nice trick, you also have couple of
more tricks on your sleeve, you can either use valueOf()
method from java.lang.String class or toString()
method from java.lang.Float class, both returns String object.
Here is Java program to parse String to floating point number in Java
and then convert back float to java.lang.String object. String
to Float Conversion Example in Java.
/**
*
* Java program to parse String to float in
Java and than convert float to
* String in Java. Remember, while converting
same value in float form and in
* String form will return different result.
For example "1".equals("1.0") will
* return false but 1 == 1.0 may return true.
*
* @author Javin Paul
*/
public class StringToFloat
{
public static
void main(String
args[]) {
// Parsing String to float in Java
// By using autoboxing Float object can be converted to
float primitive
// Converting String to Float using Float.valueOf()
method
String
strFloat = "100.1";
float fValue = Float.valueOf(strFloat);
System.out.printf("String %s is parse to float %f
in Java using valueOf %n"
, strFloat,
fValue);
// Converting String to Float using Float.parsetFloat()
method
String
strFloat2 = "150.15";
float fValue2 = Float.parseFloat(strFloat2);
System.out.printf("String %s is converted to float
%f in Java using parseFloat %n"
, strFloat2,
fValue2);
// Parse String to Float Object in Java
String
strFloat3 = "-200.2F";
Float
fValue3 = new Float(strFloat3);
System.out.printf("String %s is converted to float
object %f in Java using"
+ " Float constructor %n"
, strFloat3, fValue3);
// Second part - Converting float values to String in
Java
// Converting float data type to String in Java using +
operator concatenation
float fValue4 = 657.2f;
// remember f suffix, floating points defaults to
double in Java
String
strFloat4 = ""
+ fValue4;
System.out.printf("float %f is converted to String
%s in Java using"
+ " concatenation %n" ,
fValue4, strFloat4);
// Parsing float to String in Java using Float toString
method
Float
fValue5 = new Float(786.86f);
String
strFloat5 = fValue5.toString();
System.out.printf("Float %f is changed to String
object %s in Java using"
+ " toString %n" ,
fValue5, strFloat5);
// Converting String object to float primitive in Java -
valueOf example
float fValue6 = 919.23f;
String
strFloat6 = String.valueOf(fValue6);
System.out.printf("float %f is converted to String
%s by using valueOf"
+ " in Java %n" ,
fValue6, strFloat6);
}
}
Output:
String 100.1
is parse to float 100.099998 in Java using valueOf
String 150.15
is converted to float 150.149994 in Java using parseFloat
String -200.2F
is converted to float object -200.199997 in Java using Float constructor
float 657.200012 is converted to String 657.2 in Java using concatenation
Float 786.859985
is changed to String object 786.86 in
Java using toString
float 919.229980 is converted to String 919.23 by using valueOf in Java
That's all on this Java beginners tutorial about parsing String to
float in Java and then converting back float values to String objects. We
have learned couple of useful tricks for data type conversion, which can be
very handy while working on float and String data types
together. Just remember, both Float and String are immutable
objects in Java and any modification
on this object will result in new object.
Tidak ada komentar:
Posting Komentar