LAST UPDATED: SEPTEMBER 1, 2020
Java Float toHexString() Method
Java toHexString()
method is the part of the Float
class of the java.lang
package. This method is used to return the absolute hexadecimal equivalent String of the float value passed.
It must be noted that the value "NaN" will be returned for the Not-a-Number(NaN) float value.
Syntax:
public static String toHexString(float f)
Parameters:
The parameter passed is the float value of which the string representation of the equivalent hexadecimal is to be returned.
Returns:
Returns the String representation of the float value passed as equivalent hexadecimal value.
Example 1:
Here, a positive and a negative number is taken for a better understanding of the method.
import java.lang.Float;
public class StudyTonight
{
public static void main(String[] args)
{
float i = 132.67f;
float j = -52.45f;
System.out.println("Actual number is = " + i);
//returns the float value in hexadecimal string
System.out.println("Hexadecimal equivalent is = " + Float.toHexString(i));
System.out.println("Actual number is = " + j);
//returns the float value in hexadecimal string
System.out.println("Hexadecimal equivalent is = " + Float.toHexString(j));
}
}
Actual number is = 132.67
Hexadecimal equivalent is = 0x1.09570ap7
Actual number is = -52.45
Hexadecimal equivalent is = -0x1.a3999ap5
Example 2:
Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.print("Enter the Number = ");
Scanner sc = new Scanner(System.in);
float i = sc.nextFloat();
System.out.println("Actual Number is = " + i);
//returns the float value in hexadecimal string
System.out.println("Hexadecimal representation is = " + Float.toHexString(i));
}
catch(Exception e)
{
System.out.println("Invalid Number");
}
}
}
Enter the Number = 95.76
Actual Number is = 95.76
Hexadecimal representation is = 0x1.7f0a3ep6
***********************************************
Enter the Number = -52.911
Actual Number is = -52.911
Hexadecimal representation is = -0x1.a749bap5
***********************************************
Enter the Number = ox689
Invalid Number
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.