[java] java : convert float to String and String to float

How could I convert from float to string or string to float?

In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.

String valueFromTable = "25";
Float valueCalculated =25.0;

I tried from float to string:

String sSelectivityRate = String.valueOf(valueCalculated );

but the assertion fails

This question is related to java string types number-formatting type-conversion

The answer is


There are three ways to convert float to String.

  1. "" + f
  2. Float.toString(f)
  3. String.valueOf(f)

There are two ways Convert String to float

  1. Float.valueOf(str)
  2. Float.parseFloat(str);

Example:-

public class Test {

    public static void main(String[] args) {
        System.out.println("convert FloatToString " + convertFloatToString(34.0f));

        System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));

        System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));

        float f = Float.valueOf("23.00");
    }

    public static String convertFloatToString(float f) {
        return "" + f;
    }

    public static String convertFloatToStrUsingFloatMethod(float f) {
        return Float.toString(f);
    }

    public static String convertFloatToStrUsingStringMethod(float f) {
        return String.valueOf(f);
    }

}

To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places.

/**
 * Convert the given double to a full string representation, i.e. no scientific notation
 * and always twelve digits after the decimal point.
 * @param d The double to be converted
 * @return A full string representation
 */
public static String fullDoubleToString(final double d) {
    // treat 0 separately, it will cause problems on the below algorithm
    if (d == 0) {
        return "0.000000000000";
    }
    // find the number of digits above the decimal point
    double testD = Math.abs(d);
    int digitsBeforePoint = 0;
    while (testD >= 1) {
        // doesn't matter that this loses precision on the lower end
        testD /= 10d;
        ++digitsBeforePoint;
    }

    // create the decimal digits
    StringBuilder repr = new StringBuilder();
    // 10^ exponent to determine divisor and current decimal place
    int digitIndex = digitsBeforePoint;
    double dabs = Math.abs(d);
    while (digitIndex > 0) {
        // Recieves digit at current power of ten (= place in decimal number)
        long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
        repr.append(digit);
        --digitIndex;
    }

    // insert decimal point
    if (digitIndex == 0) {
        repr.append(".");
    }

    // remove any parts above the decimal point, they create accuracy problems
    long digit = 0;
    dabs -= (long)Math.floor(dabs);
    // Because of inaccuracy, move to entirely new system of computing digits after decimal place.
    while (digitIndex > -12) {
        // Shift decimal point one step to the right
        dabs *= 10d;
        final var oldDigit = digit;
        digit = (long)Math.floor(dabs) % 10;
        repr.append(digit);

        // This may avoid float inaccuracy at the very last decimal places.
        // However, in practice, inaccuracy is still as high as even Java itself reports.
        // dabs -= oldDigit * 10l;
        --digitIndex;
    }

    return repr.insert(0, d < 0 ? "-" : "").toString(); 
}

Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.


well this method is not a good one, but easy and not suggested. Maybe i should say this is the least effective method and the worse coding practice but, fun to use,

float val=10.0;
String str=val+"";

the empty quotes, add a null string to the variable str, upcasting 'val' to the string type.


String str = "1234.56";
float num = 0.0f;

int digits = str.length()- str.indexOf('.') - 1;

float factor = 1f;

for(int i=0;i<digits;i++) factor /= 10;

for(int i=str.length()-1;i>=0;i--){

    if(str.charAt(i) == '.'){
        factor = 1;
        System.out.println("Reset, value="+num);
        continue;
    }

    num += (str.charAt(i) - '0') * factor;
    factor *= 10;
}

System.out.println(num);

If you're looking for, say two decimal places.. Float f = (float)12.34; String s = new DecimalFormat ("#.00").format (f);


You can try this sample of code:

public class StringToFloat
{

  public static void main (String[] args)
  {

    // String s = "fred";    // do this if you want an exception

    String s = "100.00";

    try
    {
      float f = Float.valueOf(s.trim()).floatValue();
      System.out.println("float f = " + f);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

found here


I believe the following code will help:

float f1 = 1.23f;
String f1Str = Float.toString(f1);      
float f2 = Float.parseFloat(f1Str);

Float to string - String.valueOf()

float amount=100.00f;
String strAmount=String.valueOf(amount);
// or  Float.toString(float)

String to Float - Float.parseFloat()

String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or  Float.valueOf(string)

This is a possible answer, this will also give the precise data, just need to change the decimal point in the required form.

public class TestStandAlone {

    /**
     * 

This method is to main

* @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP); System.out.println("f1 --> "+f1); String s1=roundfinalPrice.toPlainString(); System.out.println("s1 "+s1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Output will be

f1 --> 152.32
s1 152.32

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean

Examples related to number-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format / Suppress Scientific Notation from Python Pandas Aggregation Results Formula to convert date to number tSQL - Conversion from varchar to numeric works for all but integer Convert string to decimal number with 2 decimal places in Java What is ToString("N0") format? format a number with commas and decimals in C# (asp.net MVC3) SSRS custom number format Format telephone and credit card numbers in AngularJS How to format a number 0..9 to display with 2 digits (it's NOT a date)

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift