Spring MVC 3 formatting BigDecimal - java

In my application, most BigDecimal numbers in forms are formatted to 2 decimal values. So I have my own BigDecimal to String converter in ConversionService (to override locale to use decimal comma instead of dot). But on specific places, i need to change that format to for example 4 decimal values. What is the best way to achieve that? I tried using #NumberFormat annotation, but I also need to use decimal comma.
Also, how does ConversionService and #NumberFormat interfere with each other in Spring MVC 3? Specifically, in <spring:form> tags? Thanks.

If your 2dp values are currency values then you might like to try wrapping them in a custom "Money" type. You could then write a formatter that displayes to 2dp but in the future it would also give you the flexibillity to introduce a currency value and possibly include that in the output. E.G. £2.99 or 2,99€.
I first read about this pattern in Martin Fowlers patterns of enterprise architecture.
http://martinfowler.com/eaaCatalog/money.html
I know it doesn't answer your specific question but I thought it might be a useful consideration that could lead you to the right answer. Hope it helps.

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.

String.format decimal with fixed width, zero padded and no decimal separator

I have a double (e.g: 123.45) and I need generate a string like 0000012345.
I'm trying to do it using only String.format (Formatter). I could use DecimalFormat and then replaceAll, but I was wondering if I could achieve the same result using formatter. The reason is that I will use it with FormatterLineAggregator (spring batch).
[EDIT] - Emphasis on the question reason. Tagged as spring batch also. Included link to spring batch documentation.
From Spring Batch doc: "... The underlying implementation is built using the same Formatter added as part of Java 5. The Java Formatter is based on the printf functionality of the C programming language. Most details on how to configure a formatter can be found in the javadoc of Formatter.".
Spring Batch itemWriter link
Could you stash the value into a Formattable and use Formattable#formatTo to generate the desired output?
As far as I know there's no way to suppress the decimal separator in a standard String.format("%f") output. Even if you add a DecimalFormatSymbolsProvider class, it must still return a char value from DecimalFormatSymbols.html#getDecimalSeparator().

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.

Can a Double be formatted without scientific notation?

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 :)

Need some help with String.format

I'm trying to find a complete tutorial about formatting strings in java.
I need to create a receipt, like this:
HEADER IN MIDDLE
''''''''''''''''''''''''''''''
Item1 Price
Item2 x 5 Price
Item3 that has a very
long name.... Price
''''''''''''''''''''''''''''''
Netprice: xxx
Grossprice: xxx
VAT: xxx
Shipping cost: xxx
Total: xxx
''''''''''''''''''''''''''''''
FOOTER IN MIDDLE
The format to pass to string.format is documented here:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
From the page:
The format specifiers for general,
character, and numeric types have the
following syntax:
%[argument_index$][flags][width][.precision]conversion
The optional argument_index is a
decimal integer indicating the
position of the argument in the
argument list. The first argument is
referenced by "1$", the second by
"2$", etc.
The optional flags is a set of
characters that modify the output
format. The set of valid flags depends
on the conversion.
The optional width is a non-negative
decimal integer indicating the minimum
number of characters to be written to
the output.
The optional precision is a
non-negative decimal integer usually
used to restrict the number of
characters. The specific behavior
depends on the conversion.
The required conversion is a character
indicating how the argument should be
formatted. The set of valid
conversions for a given argument
depends on the argument's data type.
formating string is some what complicated, for this kind of requirement.
so its better to go for some reporting tool using the format you have given.
which would be the better approach.
Either a crystal report or some others which are easy to implement.
Trying to do this with formatting a string will cost you to much time and nerves. I would suggest a templating engine like Stringtemplate or something similar.
with doing these you will separate the presentation from the data and that will be a very good thing in the long run.
See if these classes in java.text package can help..
Format
MessageFormat
Yea as solairaja said if you are planning to create reports or receipts you can go for reporting tools as Crystal reports
Crystal Report Crystal Report Tutorial
Or if you plan to use StringFormatting itself then "StringBuffer" would be the best option coz u can play around with it.
You should probably look at Java templating tools for this sort of multi-line reporting formatting.
Velocity is simple and forgiving of errors. Freemarker is very powerful but more intolerant. I would perhaps look at Velocity initially, and if you have to do more of this sort of work, take a further look at Freemarker.
Looks like the general advice from the community as a better approach to solve your problem is using a reporting tool.
Here you have a detailed list of open source Java charting and reporting tools:
http://java-source.net/open-source/charting-and-reporting
The most well known is, in my opinion, Jasper Reports. A lot of resources about it are available on the web

Categories