Floating-point hexadecimal in Java



In this article, we use the '%a' format specifier to represent floating-point numbers in their hexadecimal form. This is useful when you need precise control over the representation of floating-point values.

For Formatter, import the following package ?

import java.util.Formatter;

Now creating a 'Formatter'object to format the data?

Formatter f = new Formatter();

Using the format() method with the %a format specifier to convert a floating-point number to its hexadecimal string.?

f.format("%a", 298.45)

Example 1: Basic Example

In this example, we format the floating-point number '298.45' to its hexadecimal representation using the '%a' format specifier with a 'Formatter' object ?

import java.util.Formatter;
public class Main{
   public static void main(String args[]) {
      Formatter f = new Formatter();
      // Floating-point hexadecimal form
      System.out.println(f.format("%a", 298.45));
   }
}

Output

The above program displays the following output ?

0x1.2a73333333333p8

Example 2: Multiple Floating-Point Numbers

Following is an another example to format the multiple floating-point numbers to their hexadecimal string representations.

We iterate through an array of floating-point numbers, converting each to its hexadecimal representation using the '%a' format specifier with a 'Formatter' object ?

import java.util.Formatter;

public class Main {
   public static void main(String[] args) {
      double[] numbers = {123.456, -45.67, 0.125};
      for (double number : numbers) {
         Formatter f = new Formatter();
         f.format("%a", number);
         System.out.println(f.toString());
      }
   }
}

Output

Following is the output of the above program ?

0x1.edd2f1a9fbe77p6
-0x1.6d5c28f5c28f6p5
0x1.0p-3
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2024-12-17T23:03:20+05:30

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements