-2

Is it possible to change a float value to a String? If possible, is it also possible to converting it to a String while rounding the number to the nearest integer?

For example if I have a float such as 2.335 then, can I change it to a String of value "2.335" or "2" (by rounding it)?

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • Should `2.8` become 2 or 3 (I am assuming 3 but just want to make sure)? – Pshemo Feb 14 '16 at 10:44
  • use `String.valueOf` method – Vishrant Feb 14 '16 at 10:47
  • 3
    Please search the site before asking questions. Your question is nicely answered by [this](http://stackoverflow.com/questions/7552660/java-convert-float-to-string-and-string-to-float?rq=1) question and [this](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) one. – bcsb1001 Feb 14 '16 at 10:52

4 Answers4

2

Use java Float class:

String s = Float.toString(25.0f);

if you want to round down a number, simply use the Math.floor() function.

float f = 2.9999f;
String s = Float.toString(Math.floor(f));//rounds the number to 2 and converts to String

first line rounds the number down to the nearest integer and the second line converts it to a string.

Another way of doing this is using the String.valueOf(floatNumber);

float amount=100.00f;
String strAmount=String.valueOf(amount);
Simply Me
  • 1,579
  • 11
  • 23
1

To do this you can simply do

float example = 2.335
String s = String.valueOf(Math.round(example));
Walshy
  • 850
  • 2
  • 11
  • 32
0

To convert a float to a String:

String s = Float.toString(2.335f);

Rounding can be done via

String.format("%.5g%n", 0.912385);

which returns 0.91239

For a more elaborate answer, see Round a number in Java

Community
  • 1
  • 1
Fang
  • 2,199
  • 4
  • 23
  • 44
-1

Your first requirement can be fullfilled with String.valueOf

float f = 1.6f;
String str = String.valueOf(f);

For roundoff you can use Math.round and not Math.floor. As Math.floor will convert 1.6 to 1.0 and not 2.0 while Math.round will roundoff your number to nearest integer.

Vishrant
  • 15,456
  • 11
  • 71
  • 120