如何将 Java float
转换为字符串
原文:https://www.studytonight.com/java-type-conversion/how-to-convert-java-float-to-string
在 Java 中,我们可以通过两种方式将float
转换为String
:
通过使用 String.valueOf() 方法
通过使用 Float.toString() 方法
1.通过使用String.valueOf()
方法
()方法的值是字符串类的一部分。这是一个静态方法,将浮点转换为字符串值。
例 1:
这里,方法中传递的浮点值被转换为字符串。
public class StudyTonight
{
public static void main(String args[])
{
float n = 500.08f;
String s = String.valueOf(n);
System.out.println("The string value is " +s);
}
}
字符串值为 500.08
2.通过使用Float.toString()
方法
toString() 方法是 Float 类的一部分。这是一个静态方法,也可以用来将浮点值转换为字符串。
例 2:
这里,方法中传递的浮点值被转换为字符串。
public class StudyTonight
{
public static void main(String args[])
{
float n = 500.08f;
String s = Float.toString(n);
System.out.println("The string value is " +s);
}
}
字符串值为 500.08
3.通过使用format()
方法
我们可以使用DecimalFormat
类的format()
方法来获取浮点值的字符串值。这里,一个float
值被传递到方法中,并被转换成一个格式为 2 位数的String
。
import java.text.DecimalFormat;
public class StudyTonight
{
public static void main(String args[])
{
float n = 500.0878f;
Float f = (float)n;
String s = new DecimalFormat ("#.00").format (f); //for two places decimal
System.out.println("String is : "+s);
}
}
字符串为:500.09
4.通过使用+
运算符(连接)
我们可以使用+运算符将浮点值连接到一个空字符串,并获得一个字符串值。这里,在方法中传递一个浮点值,并使用连接将其转换为字符串。请看下面的例子。
public class StudyTonight
{
public static void main(String args[])
{
float n = 500.0878f;
String str = ""+n; //concat
System.out.println("String is : " + str);
}
}
字符串为:500.0878