Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float returning exponential notation

Tags:

java

xpath

I'm writing a bit of code for use in an Xpath query which is causing a problem. I'm trying to read a random name from a list, however the float (x) occasionally returns exponential notation.

Random r = new Random();
float x = r.nextFloat();

final String expression = "(/list/name[@minLevel<=" + minLevel + "])" +
    "[(" + x + " * count(/list/name[@minLevel<=" + minLevel + "])) +1]";

Every once in a while, expression equals something like:

(/name/list[@minLevel<=11])[(5.478859E-4 * count(/name/list[@minLevel<=11])) +1]

And apparently xpath doesn't do math with exponential notation, because I get this error:

javax.xml.transform.TransformerException: 5.478859E-4 could not be formatted to a number!

Any help on how to prevent this would be greatly appreciated.

like image 801
Richard Rhyan Avatar asked Jan 14 '23 14:01

Richard Rhyan


1 Answers

To convert the float, you could use String.format() with %f as the format specifier. This will never use scientific notation.

String.format("%f", x)

This also gives you the flexibility to tweak the width and precision as required.

like image 134
NPE Avatar answered Jan 19 '23 09:01

NPE