0

I need to print a float showing only the decimals of that float. For example:

1.23456 --> 23456
12.3456 --> 3456
123.456 --> 456

I've found the following solution:

float floatValue = 1.23455f;
String stringValue = Float.toString(floatValue);
int pointIndex = stringValue.indexOf(".");
String decimals = stringValue.substring(pointIndex + 1, stringValue.length() - 1);

But I think it's a little dirty and I wonder if there is any other standard way, using String.format or something similar. I did't find anything in the documentation. Thanks in advance!

jeojavi
  • 876
  • 1
  • 6
  • 15
  • Do you mean like `stringValue.split("\\.")[1]` for example? – Dawood ibn Kareem May 23 '14 at 11:54
  • You could always separate the fractional part of the float value and format it separately. But you'll still get the ".", I suspect. – Hot Licks May 23 '14 at 11:55
  • @HotLicks That could very well give a completely different result - the fractional part of the `float` that represents a certain decimal most accurately may not be the same as the `float` that represents the fractional part of that decimal most accurately; because `float` variables are spaced differently depending on their magnitude. – Dawood ibn Kareem May 23 '14 at 12:03
  • In fact I'm looking for a standard way, something like a formatter – jeojavi May 23 '14 at 12:17
  • @DavidWallace - Well, the OP hasn't given us the standard "it rounds wrong" gripe yet, but I'm sure it's coming. – Hot Licks May 23 '14 at 12:18

1 Answers1

1
float floatValue = 1.23455f;
String stringValue = Float.toString(floatValue).split("\\.")[1];

Should work for you

PKlumpp
  • 4,913
  • 8
  • 36
  • 64