Can a Double be formatted without scientific notation? - java

I am aware of the various posts floating out there with regards to the same issue.
Mine its a little bit different and it might be a little obvious, but I will need your comments.
I am currently using Hibernate Search and Lucene to Index entity properties.
I have a bunch of Double properties on my entities.
These entities using the default Bridges from Lucene (Bridge i.e the one in charge converting LongToString and StringToLong) are giving me troubles once the scientific notation starts to be used.
I am trying to show on DataTables on a .xhtml Credit and Debit amounts, their lenght can be as long as 18 digits, and their DataBase (DB2) type is BIGINT.
I can not change the DataBase type
to Long for example.
I can not change either the Double
type attributes of my entities
either to for example Long
So whats the question?
Is there a way from a String say "1234567890" to retrieve a Double whose format is 1234567890 and not 1.23456789E9 as it is being done by default by Double.parseDouble(FormattedString)?
PD: I am aware of the existance of DecimalFormat, however take into account using this formater will give me a String formated correctly say : "#######.E0" but what I really need is a Double with such format, however when doing Double.parseDouble(FormattedString) I will loose such format.
Hope I was clear and thanks for any help.

Is there a way from a String say "1234567890" to retrieve a Double whose value is 1234567890 and not 1.23456789E9 as it is being done by default by Double.parseDouble(FormattedString)?
Your question doesn't really make sense. 1234567890 is the same value as 1.23456789E9 and a double represents one of them, if and only if it also represents the other.
I am aware of the existance of DecimalFormat, however take into account using this formater will give me a String formated correctly say : "#######.E0" but what I really need is a Double with such format, however when doing Double.parseDouble(FormatedString) I will loose such format.
No, there is no way to construct a Double so that it is displayed in a certain way. The toString method for Double is what it is, and it can't be changed.
The only thing you can do is to for instance use DecimalFormat or String.format but as you've noted, you'll always end up with a String.

Don't know nothing of Lucene, but you can never have a Double in a .xhtml Document it is always a characterstring. A Double doesn't have a Format, only a String representation of a Double has.

So I finally got the solution to my problem.
After rounding up what aioobe and Jens Schauder said. I am able to format the text dynamically on my .xhtml with the following tag:
<h:outputText value="#{recordTable[column.property]}"
rendered="#{column.header ne 'Details' and
column.header eq ('Total Credit Amount' or
'Total Debit Amount')}">
<f:convertNumber pattern="########"/>
</h:outputText>
Thanks for making clear to me these basic stuff I had blurred :)

Related

Locale specific BigDecimal formatting in GWT

I've tried coming up with a solution to this problem by combining a few separate issues other people posted on this site, but somehow can't get it right.
I receive a BigDecimal from the server which I need to display in a TextBox inside a GWT page.
BigDecimal bigDec = new BigDecimal(type.mb3.toString()).setScale(2, BigDecimal.ROUND_HALF_UP);
t12.setText(bigDec.toString());
After this call the TextBox displays ex. 1200.00, which is the correct value, however I would like for it to be formatted with a German locale ##0,00.
I can't convert it by specifying the format via NumberFormat, as it doesn't accept BigDecimal. Is there another way I can format this without writing a neanderthal "if you see dot exchange it for comma" text parser?
The comment Thomas Broyer provided was the answer. I needed to use java.lang.Number instead of pure BigDecimal and it formatted correctly.

DecimalFormat weird behavior with pattern #####0.00 in Java

I am using below code snap to display float price value with two decimal points.
NumberFormat FORMAT = new DecimalFormat("#####0.00");
float myFloatValue =\\I am able to fetch this value dynamically
String finalPrice = FORMAT.format(myFloatValue);
// I am using this String (finalPrice) for export xml purpose.
It seems working fine normally, but I have noticed some examples(given below) where it is not working properly and produce the price with more than two decimal points. I am not able to replicate it again, I can see it in only log files.
Some examples output of finalPrice String : 0.10999966, 0.1800003, 0.45999908.
Can anybody help me to guess original value of myFloatValue from these outputs? So that it will help me to replicate the scenario and fix it.
The sporadic occurrence makes me wonder whether the DECIMAL_FORMAT is used in several threads concurrently. That is a no-no. However one would expect
wrong values too.
Maybe for good order also specify a fixed Locale (decimal point vs. comma, thousand separators).
And finally float or even double are not suited for financial software: those numbers are approximations.
BigDecimal price = new BigDecimal("9.99");
price = price.multiply(BigDecimal.TWO); // 19.98 exact
BigDecimal is a PITA for writing calculations, but keeps its precision.

Inserting custom String between number and decimal - Java DecimalFormat

Hello and thank you in advance for the help.
I am having some trouble formatting using a Java function to mark up a price in HTML.
It seems that, no matter what I do, I cannot insert custom content between the numbers and the decimal (throws Illegal Argument Exception). Is there any known way to achieve the following:
NumberFormat nf = getNumberFormat("'<span class=\"dollars\">'##'</span></span class=\"decimal\">'.'</span></span class=\"cents\">'00'</span>'", locale);
nf.format(number);
Assume locale and number are correctly initialized.
If you look at the docs for DecimalFormat you'll see that they talk about the prefix and the suffix text - but not putting arbitrary text within a number.
It sounds like you should basically write this bit of formatting yourself - possibly using DecimalFormat for each section of the number.
You might consider using String.format(String pattern, Object... arguments). You can pass your simply formatted numbers as arguments.

Parse BigDecimal from String containing a number in arbitrary format

We read data from XLS cells formatted as text.
The cell hopefully contains a number, output will be a BigDecimal (because of arbitrary precision).
Problem is, the cell format is also arbitrary, which means it may contain numbers like:
with currency symbols ($1000)
leading and trailing whitespaces, or whitespaces in between digits (eg. 1 000 )
digit grouping symbols (eg. 1,000.0)
of course, negative numbers
'o's and 'O's as zeros (eg. 1,ooo.oo)
others I can't think of
It's mostly because of this last point that I'm looking for a standard library that can do all this, and which is configurable, well tested etc.
I looked at Apache first, found nothing but I might be blind... perhaps it's a trivial answer for someone else...
UPDATE: the domain of the question is financial applications. Actually I'm expecting a library where the domain could be an input parameter - financial, scientific, etc. Maybe even more specific: financial with currency symbols? With stock symbols? With distances and other measurement units? I can't believe I'm the first person to think of something like this...
I don't know any library, but you can try that:
Put your number on a string. (ex: $1,00o,oOO.00)
Remove all occurrences of $,white-spaces or any other strang symbols you can think of...
Replace occurrences of o and O.
Try to parse the number =]
That should solve 99% of the entrys...
Buy bunch photos or even better videos with legal adult content. Create a web site with these resources but limit the access with captcha which will be displaying unsolved number formats. Create a set of number decoders out of known number formats and create an algorithm which will add new ones based on user solved captchas.
I think this is what I've been looking for:
http://site.icu-project.org/
Very powerful library, although at the moment it's not clear whether it can only format or all the formatted stuff can be parsed back as well.

Java string to double conversion

I've been reading up on the net about the issues with handling float and double types in java. Unfortunately, the image is still not clear. Hence, i'm asking here direct. :(
My MySQL table has various DECIMAL(m,d) columns. The m may range from 5 to 30. d stays a constant at 2.
Question 1.
What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I've settled with double - hence this post).
Question 2.
While trying to parse a double from a string, i'm getting errors
Double dpu = new Double(dpuField.getText());
for example -
"1" -> java.lang.NumberFormatException: empty String
"10" -> 1.0
"101" -> 10.0
"101." -> 101.0
"101.1" -> 101.0
"101.19" -> 101.1
What am i doing wrong? What is the correct way to convert a string to a double value?
And what measures should i take to perform operations on such values?
EDIT
This is the code -
System.out.println(dpuField.getText());
Double dpu = new Double(dpuField.getText());
System.out.println(dpu);
Yes, the problem lies with getText() reporting the wrong value of the dpuField.
This method is called on the JTextField keyTyped event. So what's going wrong here?
EDIT 2
Looking at :
http://journals.ecs.soton.ac.uk/java/tutorial/post1.0/ui/keylistener.html
Apparently, keyTyped() does not give me the keycode. I'll have to switch to keyRealeased()
What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I've settled with double - hence this post).
Since it's a DECIMAL field, you should prefer java.math.BigDecimal. You can store it in DB using PreparedStatement#setBigDecimal() and you can retrieve it from DB using ResultSet#getBigDecimal().
While trying to parse a double from a string, i'm getting errors
This can't be true. The problem lies somewhere else. Maybe it is just not returning the data you expect to be returned or you are not using/debugging the values you expect them to be.
if you need exact precision without rounding errors, you should use a BigDecimal.
Your code looks OK - could it be that dpuField.getText() somehow cuts the last character from the string values you list above?
Update: you say
Yes, the problem lies with getText() reporting the wrong value of the dpuField. This method is called on the JTextField keyTyped event.
Could it be that getText() returns the value of the field before the last typed key is actually appended to it?
For decimal, I believe you risk losing precision if you don't use a BigDecimal on the Java side, as some decimal fractions can't be stored as a binary fraction.
Prefer Double.valueOf(String) over the constructor, but that's a valid way. Something else must be going on (i.e. I doubt those are the actual String values you're passing in).
Question1: It's bad idea to map DECIMAL columns to Double, usually the BigDecimal is the correct type. http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html#1055175
Question 2: You are doing something wrong; print the String value before converting.

Categories