0

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.

5
  • 5
    But I found if the Float value = 100.00; If String value will be 100.0. Confusing. Commented Sep 18, 2013 at 10:03
  • 1
    what u want 100 or 100.00 ? Commented Sep 18, 2013 at 10:06
  • 2
    You know, that "exact" is a quite broad term, when using floating point arithmetic? Commented Sep 18, 2013 at 10:07
  • Using the word exact in the context of floating numbers triggers me to link What Every Computer Scientist Should Know About Floating-Point Arithmetic Commented Sep 18, 2013 at 10:09
  • @Pawanmishra what i want is when i set the float value = 100.0, it will output 100.0, when the float value = 100.00,it will be 100.00.So is this can implemented? Commented Sep 22, 2013 at 7:43

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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 ...

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.