Reputation: 376
I'm using an Oracle DB
together with JDBC. I have to select some values and write them to a file.
First I used ResultSet#getString
which gave me almost all values formatted as desired except sometimes numbers were represented with an exponential. E.g.: 0.0897234E-4
In order to get rid of the exponential I checked if the type of the current column is NUMERIC and then used ResultSet#getBigDecimal
to get a BigDecimal. I've done that because there are all kinds of Java number types stored in the DB and as Oracle DB only provides NUMERIC as type for numbers, I have to use the BigDecimal because every numeric Java type can be stored in a BigDecimal.
Then I used the BigDecimal#toPlainString
method to effectively get rid of the exponential.
if (rset.getMetaData().getColumnType(i) == java.sql.Types.NUMERIC) {
value = (rset.getBigDecimal(i) != null rset.getBigDecimal(i).toPlainString() : "0");
}
The next problem was, that I then got a leading zero when the number was below 1 but I don't want them.
.007346
<-- desired0.007346
-.4352
<-- desired-0.4352
To deal with that problem I searched the internet and found the DecimalFormat
class. I was then able to format the numbers so that I don't have leading zeros with the following format:
new DecimalFormat("#.");
But this of course didn't display any digits after the decimal point but does add a decimal point after every number. E.g.: 1235.
-65.
So what I want is, that if the number is decimal there should be as much digits as needed (actually 38, I think is in Oracle DB the max). There should never be exponentials and if the number is below 1 there shouldn't be a leading zero. If the number is natural there shouldn't be a decimal point at the end.
Some examples of the desired format:
9873478
-1349
.743803
-.004726
How can I achieve such a representation? Any solution is welcome I don't have to use the DecimalFormat. Could the solution possibly be, that I have to determine the type after getting the number as a BigDecimal by trying to convert it to the different Java types?
Upvotes: 4
Views: 2231
Reputation: 5489
What about new DecimalFormat(".#");
?
You were very close to the answer, indeed. As you can see the behaviour of the decimals in your attempt is the behaviour you expected on the integer part.
As you can read in Javadoc #
shows zero as absent
EDIT
As stated in the comments, the problem with the solution above is that you get only one decimal. You'd maybe better define your layout by the API rather than with a pattern.
DecimalFormat format = new DecimalFormat();
format.setMinimumIntegerDigits(0);
format.setMaximumFractionDigits(2000);//should be more than enough
Note that you could also improve the first solution
DecimalFormat format = new DecimalFormat(".##################################################################");
...but it is less easy to define a large number of fraction digits (if you really need it).
Upvotes: 5