Using Java’s Float class.
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.)
Answer from Petar Ivanov on Stack OverflowConvert float to String and String to float in Java - Stack Overflow
How to convert String to a float? I know for new Float( ) or Float.parseFloat( ) or Float.valueOf( ) tricks, but they don't work.
converting string to float....
Simple and clean java float to string conversion - Stack Overflow
Videos
Using Java’s Float class.
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.)
Float to string - String.valueOf()
float amount=100.00f;
String strAmount=String.valueOf(amount);
// or Float.toString(float)
String to Float - Float.parseFloat()
String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or Float.valueOf(string)
I need to put a String in sePrice(float price) setter, but then I get this error: Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: class java.lang.Float cannot be cast to class java.lang.String (java.lang.Float and java.lang.String are in module java.
public class Product {private SimpleStringProperty name;private SimpleFloatProperty price;
//I need to to a String here from another method and then convert it to a float.
public void setPrice(float price) {this.price.set(price);}}
I need to use SimpleFloatProperty because I use TableVIew.
System.out.println(String.format("%.1g%n", 0.9425));
System.out.println(String.format("%.1g%n", 0.9525));
System.out.println(String.format( "%.1f", 10.9125));
returns:
0.9
1
10.9
Use the third example for your case
Stupid roundabout way of doing it:
float myFloat = 33.33f;
int tenTimesFloat = (int) (myFloat * 10); // 333
String result = (tenTimesFloat / 10) + "." + (tenTimesFloat % 10); // 33.3
Note that this truncates the number, so 10.99 would convert to 10.9. To round, use Math.round(myFloat * 10) instead of (int) (myFloat * 10). Also, this only works for float values that are between Integer.MAX_VALUE/10 and Integer.MIN_VALUE/10.