2

This is a very simple question, but I'm amazed on how difficult it has been to answer. Even the documentation didn't give a clear and straight answer.

You see, I'm simply trying to convert a simple float to a string such that the result only has one decimal digit. For example:

String myfloatstring = "";
float myfloat = 33.33;
myfloatstring = Float.toString(myfloat);

This does indeed return "33.33". This is fine, except I'm looking for a way to get it to truncate the decimal to "33.3". It also needs to impose a decimal whenever a whole number is put in. If myfloat was 10, for example, it would need to display as "10.0". Oddly not as simple as it sounds.

Any advice you can give me would be greatly appreciated.

EDIT #1:

For the moment, I'm not concerned with digits to the left of the decimal point.

3
  • 3
    See DecimalFormat Commented Jun 10, 2015 at 15:14
  • 1
    possible duplicate of How to round a number to n decimal places in Java Commented Jun 10, 2015 at 15:20
  • Also, if you want more control over the actual values so you can round or display exactly how you like, one technique is to use an integer and pure scalar math, and then place the decimal point where it belongs on display only. Commented Jun 10, 2015 at 15:53

2 Answers 2

4
System.out.println(String.format("%.1g%n", 0.9425));
System.out.println(String.format("%.1g%n", 0.9525));
System.out.println(String.format( "%.1f", 10.9125));

returns:

0.9
1
10.9

Use the third example for your case

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

2 Comments

I tried that with a value of 10. This solution returned '1e+01'.
Okay, this was just a quick example to point you towards the String.format() method. I've added another more applicable example
0

Stupid roundabout way of doing it:

float myFloat = 33.33f;
int tenTimesFloat = (int) (myFloat * 10); // 333
String result = (tenTimesFloat / 10) + "." + (tenTimesFloat % 10); // 33.3

Note that this truncates the number, so 10.99 would convert to 10.9. To round, use Math.round(myFloat * 10) instead of (int) (myFloat * 10). Also, this only works for float values that are between Integer.MAX_VALUE/10 and Integer.MIN_VALUE/10.

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.