Program to convert String to Float in java (example)

Converting strings to floats involves transforming textual representations of numerical values into their corresponding floating-point counterparts. In programming, this process is crucial for handling data precision with smaller decimal values. This has application in variety of real time applications.

Financial applications, such as stock market analysis or currency conversions, benefit from float conversions, handling vast datasets more efficiently. Additionally, in graphical applications like gaming or simulations, where rapid computations occur, utilizing floats enhances performance. String-to-float conversion ensures accurate representation of smaller decimal values, enabling these applications to operate swiftly and effectively.

Java offers a method, Float.parseFloat(), specifically designed to convert strings containing numeric representations into their float counterparts. Also, Java’s Float.valueOf()  is another to achieve string to float conversion. Further, Java’s Scanner class, has nextFloat method which return float value of given input string.

Let’s explore these method to convert String to Float.

1. Convert String to float  – Float.parseFloat

The Float.parseFloat() method is a straightforward way to convert a string to a float in Java. It takes a string argument representing a numeric value and returns the equivalent float value. It will throw a NumberFormatException if the string does not represent a valid float value or contains non-numeric characters.

public class StringToFloat {
    public static void main(String[] args) {
        String fuelPriceStr = "3.14";
        float fuelPrice = Float.parseFloat(fuelPriceStr);

        System.out.println("String value (Fuel Price): " + fuelPriceStr);
        System.out.println("Float value (Fuel Price): " + fuelPrice);
    }
}

Real time Example – GPS Coordinate Processing :

A GPS navigation system receives latitude and longitude coordinates as strings and requires conversion to float values for accurate positioning.

public class GPSProcessing {
    public static void main(String[] args) {
        String latitudeStr = "37.7749"; 
        String longitudeStr = "-122.4194"; 

        float latitude = Float.parseFloat(latitudeStr);
        float longitude = Float.parseFloat(longitudeStr);

        // Process and utilize the latitude and longitude coordinates
        System.out.println("Latitude (String): " + latitudeStr);
        System.out.println("Longitude (String): " + longitudeStr);
        System.out.println("Latitude (Float): " + latitude);
        System.out.println("Longitude (Float): " + longitude);

        // Perform GPS navigation calculations or location-based services
        // Example: Calculate distance, plot on maps, provide directions, etc.
    }
}

2. Method – convert String to Float in java (example)

The Float.valueOf() method creates a Float object from a string and then extracts its float value. This approach allows for more flexibility with the Float object’s methods.
The returned Float object can be utilized in an object-oriented context, enabling functionalities such as interaction with collections, utilization of object-specific methods (e.g., compareTo(), equals(), toString()), and compatibility with object-based paradigms. Additionally, enables to use in collections like Hashmap as a Key or Value.

        String mobilePriceStr = "4.75";
        Float mobilePriceObj = Float.valueOf(mobilePriceStr);
        float mobilePrice = mobilePriceObj.floatValue();

Real time Example: Financial Stock Price Analysis

A financial analysis tool receives stock prices as strings from various sources and requires converting them to float values for comprehensive market analysis.

public class StockPriceAnalysis {
    public static void main(String[] args) {
        String stockPriceStr = "145.20"; 

        Float stockPriceObj = Float.valueOf(stockPriceStr);
        float stockPrice = stockPriceObj.floatValue();

        // Analyze the stock price and perform financial market calculations
        System.out.println("Stock Price (String): " + stockPriceStr);
        System.out.println("Stock Price (Float): " + stockPrice);

        // Perform financial analysis, trends, comparisons, etc., using the float value
        // Example: Calculate returns, assess trends, generate reports, etc.
    }
}

3. Method – convert String to float in java (example)

Java’s Scanner class provides the facility to structured input, including numeric values, from strings. By utilizing the nextFloat() method of the Scanner class, we can extract float values from strings with various formatting or patterns.

The Scanner class tokenizes the input string based on specific delimiters, allowing extraction of float values or other data types according to defined patterns. Scanner class supports operations on input streams, enabling parsing of numeric values not only from strings but also from other sources such as files or user inputs via the console.

Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter the fuel price: ");
        String fuelPriceStr = scanner.nextLine();

         // Converting string to float
        float fuelPrice = Float.parseFloat(fuelPriceStr);

Real time Example – Bar Code Scanner:

A retail store uses a barcode scanner that reads product prices as strings, and these prices need to be converted to float values for billing and inventory management.

import java.util.Scanner;

public class RetailPriceScanner {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Scan the product price: ");
        String productPriceStr = scanner.nextLine();

        float productPrice = Float.parseFloat(productPriceStr);

        // Process the product price for billing and inventory management
        System.out.println("Product Price (String): " + productPriceStr);
        System.out.println("Product Price (Float): " + productPrice);

        // Use the float value for billing transactions, updating inventory, etc.
        // Example: Calculate total bill, track inventory, manage sales, etc.
    }
}

Summary: String to float/Float:

there are various methods to perform String to float/Float conversion and each solve particular purpose. We can use these methods to convert String to float/Float data types.

Scroll to Top