Float to string


What is the need of converting primitive float or Float wrapper-type to String ?

  • Generally, whenever we receive or send data from web application then it all passed in the form of String only
  • After mathematical calculation, all numbers need to be converted into String for displaying
  • This article explains about primitive float data-type or Float wrapper-type to String conversion only, but we can do conversion for other types like long, double, int, etc. to String object
  • Note: Likewise, sometimes String to Float conversion is also required

 

  1. using Float.toString(floatValue);
  2. using String.valueOf(floatValue);
  3. using String.format(type, floatValue);
  4. create Float object and then convert to String using toString() method {new Float(floatValue).toString();}
  5. adding double quotes (“”) to float value {i.e.; “” + floatValue;}
  6. using append() method of StringBuffer & StringBuilder

 

Auto-boxing and un-boxing feature from Java 1.5 version:


  • parseFloat() method returns primitive float data-type, but it can be easily used as Float wrapper-type
  • as auto-boxing feature helps to convert primitive data-type to wrapper-types
  • similarly, Float.valueOf() method returns Float wrapper-type, but it can also be used as primitive float
  • let’s see one example on this auto-boxing feature

 

Read String class in detail with example

 

Let us move forward and discuss all possible ways to convert Float to String in Java

Way 1: Using Float.toString(floatValue); method

  • This method can be used to convert primitive float data-type or Float wrapper-type to String object
  • Negative float data-type can also be converted to String type, as shown in the below example

Method signature:

  public static String toString(float f);  

 

ConvertFloatIntoStringUsingToStringMethod.java

Output:

 

Way 2: Using String.valueOf(floatValue); method

  • This method can be used to convert primitive float data-type or Float wrapper-type to String object
  • Negative integer data-type can also be converted to String type, as shown in the below example

Method signature:

 

ConvertFloatIntoStringUsingValueOfMethod.java

Output:


 

Way 3: Using String.format(type, number); method

  • This method can be used to convert primitive float data-type or Float wrapper-type to String object
  • Negative integer data-type can also be converted to String type, as shown in the below example

Method signature:

 

ConvertFloatIntoStringUsingFormatMethod.java

Output:

 

Way 4: create Float object and then convert to String invoking toString() method

  • Here, we will create new Float object with primitive float value as constructor-argument
  • After creating new Float object by passing primitive float value, then invoke toString() method for converting primitive float data-type to String object

Method signature:

 

ConvertFloatIntoStringUsingObjectCreation.java

  package in.bench.resources.floating.to.string.conversion;    public class ConvertFloatIntoStringUsingObjectCreation {    	public static void main(String[] args) {    		// primitive float data-type  		float fValue1 = 87.5421f;    		// 1. converting float to String by creating Integer object   		Float floatObj1 = new Float(fValue1);    		// and then invoke toString(); method  		String str1 = floatObj1.toString();  		System.out.println("1. Converted primitive float to String value is : "  				+ str1);      		// primitive float data-type (negative value)  		float fValue2 = -8754.21f;    		// 2. converting negative int to String by creating Integer object  		Float floatObj2 = new Float(fValue2);    		// and then invoke toString(); method  		String str2 = floatObj2.toString();  		System.out.println("n2. Converted negative primitive float to String value is : "  				+ str2);      		// Float object  		Float fValue3 = new Float(1.4785f);    		// 3. converting Float object to String by creating Float object  		String str3 = fValue3.toString();  		System.out.println("n3. Converted Float object to String value is : "  				+ str3);      		// converted and then concatenated strings using + operator  		System.out.println("nFinal concatenated floating strings : ");  		System.out.println(str1 + " " + str2 + " " + str3);  	}  }  

Output:


  1. Converted primitive float to String value is : 87.5421    2. Converted negative primitive float to String value is : -8754.21    3. Converted Float object to String value is : 1.4785    Final concatenated floating strings :   87.5421 -8754.21 1.4785  

 

Way 5: adding double quotes (“”) to float value

Note: for this conversion to work, double-quotes (“”) must be added at the start of the concatenation

Syntax:

  String temp = “” + floatValue;  

 

ConvertFloatIntoStringByAddingDoubleQuotes.java

  package in.bench.resources.floating.to.string.conversion;    public class ConvertFloatIntoStringByAddingDoubleQuotes {    	public static void main(String[] args) {    		// primitive float data-type  		float fValue1 = 98.5632f;    		// 1.  

nverting float to String by adding "" String str1 = "" + fValue1; System.out.println("1. Converted primitive float to String value is : " + str1); // primitive float data-type (negative value) float fValue2 = -9856.32f; // 2. converting negative float to String by adding "" String str2 = "" + fValue2; System.out.println("n2. Converted negative primitive float to String value is : " + str2); // Float object Float fValue3 = new Float(5.4321f); // 3. converting Integer object to String by adding "" String str3 = "" + fValue3; System.out.println("n3. Converted Float object to String value is : " + str3); // converted and then concatenated strings using + operator System.out.println("nFinal concatenated floating strings : "); System.out.println(str1 + " " + str2 + " " + str3); } }

Output:

  1. Converted primitive float to String value is : 98.5632    2. Converted negative primitive float to String value is : -9856.32    3. Converted Float object to String value is : 5.4321    Final concatenated floating strings :   98.5632 -9856.32 5.4321  

 

Way 6: Using append() method of StringBuffer & StringBuilder

  • This method can be used to convert primitive float data-type to String object
  • Only sign is allowed, like minus (-)

Syntax:

  StringBuffer sb = sb.append(floatValue);    String temp = sb.toString();  

 

ConvertFloatIntoStringByAppending.java

  package in.bench.resources.floating.to.string.conversion;    public class ConvertFloatIntoStringByAppending {    	public static void main(String[] args) {    		// primitive float data-type  		float fValue1 = 21.3659f;    		// 1. converting float to String by using append() method  		StringBuffer sb1 = new StringBuffer();  		String str1 = sb1.append(fValue1).toString();  		System.out.println("1. Converted primitive float to String value is : "  				+ str1);      		// primitive float data-type (negative value)  		float fValue2 = -2136.59f;    		// 2. converting negative float to String by using append() method  		StringBuffer sb2 = new StringBuffer();  		String str2 = sb2.append(fValue2).toString();  		System.out.println("n2. Converted negative primitive float to String value is : "  				+ str2);      		// Float object  		Float fValue3 = new Float(867.514f);    		// 3. converting Float object to String by using append() method  		StringBuffer sb3 = new StringBuffer();  		String str3 = sb3.append(fValue3).toString();  		System.out.println("n3. Converted Float object to String value is : "  				+ str3);      		// converted and then concatenated strings using + operator  		System.out.println("nFinal concatenated floating strings : ");  		System.out.println(str1 + " " + str2 + " " + str3);  	}  }  

Output:


  1. Converted primitive float to String value is : 21.3659    2. Converted negative primitive float to String value is : -2136.59    3. Converted Float object to String value is : 867.514    Final concatenated floating strings :   21.3659 -2136.59 867.514  

 

www.benchresources.net

Example: Converting float to String

In this program we have two float variables, we are converting them to strings using different-2 methods. We are converting first float variable to string using valueOf(float) method while we are using toString(float) method to convert the second float variable. This example demonstrates the use of both the above mentioned methods.

package com.beginnersbook.string;    public class FloatToString {      public static void main(String[] args) {          /* Method 1: using valueOf() method           * of String class.           */          float fvar = 1.17f;          String str = String.valueOf(fvar);          System.out.println("String is: "+str);                    /* Method 2: using toString() method            * of Float class           */          float fvar2 = -2.22f;          String str2 = Float.toString(fvar2);          System.out.println("String2 is: "+str2);      }  }

Output:

String is: 1.17  String2 is: -2.22

beginnersbook.com

You can also use this (shorter):

float f = 3.1415927; char buf[10]; // Put whatever length you need here String(f).toCharArray(buf,10);

Some things to note:

  1. This will create and destroy a String object each time. This can be bad for your heap.
  2. At least on Arduino, doing this often enough will crash the program due to heap fragmentation/exhaustion.
  3. The length specified in the toCharArray second argument (10 in this case) is the size of the character array. The particle implementation of this function appears to always create a number that fills the space with the following priorities: There is always a trailing NULL. If the number is negative, a sign will occupy the first character in the array. The integral part of the number is expressed next. Finally, as many decimal digits as will fit are enumerated into the remaining slots in the array.
  4. This has the effect of rendering value such as 42.5 = 42.500000 but in some cases, e.g. 25.8 = 25.799999.

Unfortunately, there does not appear to be a way to indicate that you want a particular number of decimal places in this method.

The dtoa() function appears not to be available in the local IDE, nor is dtostrf(). At least in the version I downloaded on July 24, sprintf with %f does not work (silently renders empty field). The cloud IDE does not appear to be working at the moment (compile attempts result in a 404 error message).

The general prototype for dot appears to be as follows:

dtoa(floating_point_value, mode (you probably want mode 0), decimal_digits, &decpt, &sign, **result)

I wasn’t able to find any real documentation for &decpt, &sign, or the format of **destination. It appears that these are actually return values. (decpt and sign are (uint8_t *) and specify the place for the function to place those values, whatever they are and result is type (char **) such that the function dynamically allocates a char[] to hold the result and then places a pointer to that in the location specified by result. (*result[0] = first character of result).

community.particle.io


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте как обрабатываются ваши данные комментариев.