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.
Read more »
0 komentar:
Posting Komentar