Sstx
Sstx

Reputation: 604

How to parse Float to String exactly?

As the title said:

I tried:

        Float.toString(float);
        String.valueOf(float);
        Float.toHexString(float);
        float.toString();

But I found if the Float value = 100.00; Covert to String value will be 100.0. How to avoid it? How to be exactly?

Thanks in advance.

Edits-------------

The answers are point to that those which specific the decimal places.

Upvotes: 0

Views: 257

Answers (4)

Georgi Eftimov
Georgi Eftimov

Reputation: 124

float f = 100.00000f;
String expected = String.format("%.6f", f);

The output of this will be :

100.000000

The length of the numbers after the floating point is done by you.

String.format("%.6f", f) == 100.000000

String.format("%.2f", f) == 100.00

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

if you are bent upon doing this..

when you get str = "100.0";

 String[] strNew = str.split(".");

 if(strNew[1].length==1)
 {
 str=str+"0";
 }

BTW A VERY BAD WAY ...

Upvotes: 0

Julien
Julien

Reputation: 2584

To be exact, you'd better try to format your Float to String using the NumberFormat class hierarchy : http://docs.oracle.com/javase/6/docs/api/java/text/NumberFormat.html

Upvotes: 4

Reinherd
Reinherd

Reputation: 5506

Its "stupid" to keep 2 zeros at the end. All you've to do is add as many zeros as needed at the moment you're printing it, but internally, it's going to be saved as x.0

Example:

printf ("%.2f", 3.14159);

Prints:

3.14

Upvotes: 1

Related Questions