当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Float toString()用法及代码示例


Java Float 类的 toString() 方法返回此 Float 的字符串说明。

与此 Float 对应的原始 float 值转换为 String,与通过一个参数的 toString() 方法所做的相同。

用法:

public String toString()

参数:

NA

返回值:

toString() 方法返回此 Float 对象的字符串说明。

例子1

public class FloatToStringExample1 {

    public static void main(String[] args) {

        Float f1=9876f;

        System.out.println("1. "+f1+" Converted to String = "+f1.toString());

        Float f2=1001f;

        System.out.println("2. "+f2+" Converted to String = "+f2.toString());

       // instead of adding it will concatenate the two strings

        String f3=f1.toString()+f2.toString();

        System.out.println("3. Concatenated String = "+f3);

    }

}

输出:

1. 9876.0 Converted to String = 9876.0
2. 1001.0 Converted to String = 1001.0
3. Concatenated String = 9876.01001.0

例子2

import java.util.Scanner;


public class FloatToStringExample2 {

    public static void main(String[] args) {

        Scanner scanner=new Scanner(System.in);

        System.out.print("Enter your password:");

        Float f1 =scanner.nextFloat();

        //calling static toString() method

        String f2 = Float.toString(f1);

        System.out.println("Your password + 18 = "+f2+18);
    }
}

输出:

Enter your password:923
Your password + 18 = 923.018

例子3

public class FloatToStringExample3 {
    public static void main(String[] args) {
        int f1 = Float.MIN_EXPONENT;
        int f2 = Float.MAX_EXPONENT;
        String f3 = Float.toString(f1)+Float.toString(f2);
        System.out.println("1. Sum =  "+f3);
        System.out.println();
        Float f4=Float.NEGATIVE_INFINITY;
        System.out.println("String value = "+f4.toString());
        Float f5= Float.MAX_VALUE;
        System.out.println("String value = "+f5.toString());
        String s2 = f4.toString()+f5.toString();
        System.out.println("2. Sum = "+s2);
   }
}

输出:

1. Sum =  -126.0127.0

String value = -Infinity
String value = 3.4028235E38
2. Sum = -Infinity3.4028235E38






相关用法


注:本文由纯净天空筛选整理自 Java Float toString() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。