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.

Miles Peterson
  • 265
  • 1
  • 4
  • 12
  • 3
    See [DecimalFormat](https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html) – GriffeyDog Jun 10 '15 at 15:14
  • 1
    possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – Brian H Jun 10 '15 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. –  Jun 10 '15 at 15:53

2 Answers2

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

Brian H
  • 1,033
  • 2
  • 9
  • 28
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.

Sizik
  • 1,066
  • 5
  • 11