How to format Numbers in Velocity Templates? - java

I am getting a java object in my velocity template. The object has a double value which I want to format to 2 decimal places and display it in my template.
The class for which im getting an object is something like this
Class Price
{
double value;
String currency;
}
In my velocity template, im getting the value like this
$price.value
but I need to format it to 2 decimal places before displaying it.
I want to convert
23.59004 to 23.59
35.7 to 35.70
3.0 to 3.00
9 to 9.00
Please tell me how can I do it in velocity template? I searched a lot for this and found that I can use velocity tools, but there are no examples related to it? and can i use velocity tools in templates?

Velocity tools are expected to be used in Velocity templates; essentially they are objects added to the variables available in a template so that you can use $numberTool.format("#0.00", $val) or similar. If none of the available tools don't fit your needs, simply create a POJO and add it to the template.
To make it working you also should add the following maven dependency:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
and write following code:
context.put("numberTool", new NumberTool());

#set($String = "abc")
$String.format("%.2f", $val)
$val has to be Double or Float in this case...

formatCurrency($value). This is good java velocity code to format a number to currency format.

Use the MathTool from the VelocityTools project.
$math.roundTo(2, $val)

Solution by just using the Java Formatters: (without additional libraries)
NumberFormat decimalFormat = new DecimalFormat("#.00");
velocityContext.put("decimalFormat", decimalFormat);
Int Number: $decimalFormat.format($obj.intNum)
And here is how the timestamp is formatted to human readable date.
DateFormat DATETIME_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
velocityContext.put("datetimeFormat", DATETIME_FORMAT);
Timestamp to Date: $datetimeFormat.format($obj.timestamp)

$numberTool.format("#0.00", $val)

A better way to do things besides using $numberTool.format is to use one of the MessageFormat-based tool classes that do more than just numbers. For example, we use MessageTool which is Struts-specific, but you can use something similar like ResourceTool instead:
resources.properties
some.key=The price is currently {0,number,$#.##}
template.vm
<p>
$msg.get('some.key', 'resources', [$price])
</p>
This way, you get the number in context and not just all by itself. In a non-English language, the number might be more appropriate to come to the left of the text, or in the middle, or whatever. This gives you much more flexibility than simply formatting the number all by itself.

Related

How to customize number format in freemarker?

I am using freemarker and trying to display numbers in this format: $3,343,434.00 for example. This was easily taken care of by using ${total?string.currency} (assuming "total" is some number).
However, when I have negative numbers, it's showing them like this: ($343.34) instead of this: -$343.34. I need the negative sign instead of the parenthesis. Is there a way I could customize the formatting so it does everything that the string.currency did but replace the negative value behavior? I am relatively new to freemarker, so detailed responses are appreciated!
You can also try ?string(",##0.00"). However in this case you need to explicitly add $ and - sign would be after $ in case of negative numbers.
<#local total = 3343434/>
$ ${total?string(",##0.00")} //$ 3,343,434.00
<#local total = -3343434/>
$ ${total?string(",##0.00")} //$ -3,343,434.00
OR in case if you want what was expected you can replace the strings.
<#local total = -3343434/>
<#local total = "$ " + total?string(",##0.00")/>
${total?replace('$ -','- $')} //- $3,343,434.00
Update: Since FreeMarker 2.3.24 you can define named custom number formats, which can be an alias to a number format pattern (or even a formatter implemented in Java, but that level of flexibility isn't needed in this case). So add a custom number format called "money" as an alias to "¤,##0.00" to the FreeMarker configuration, and then you can write something like ${total?string.#money}. See: http://freemarker.org/docs/pgui_config_custom_formats.html
Currently FreeMarker just uses the formatting facility of the Java platform, so it's only as configurable as that (assuming you want to use ?string and ?string.somethingPredefiendHere). Which is not much... but, in general, the formatting categories provided by the Java platform is not fine-gradient enough anyway, I mean, you don't have application-domain categories like, price-of-product, a salary, a price on the stock, etc. (This demand is more frequent with non-currency numbers though.) So I think, generally, you want to make a formatter function, that you can use like ${salary(someNumber)}, ${price(someNumber)}, etc. Those functions can be implemented in a commonly #included/#imported template like a #function or in Java by using #assign salary = 'com.example.SalarayMethod'?new() in place of #function, where com.example.SalarayMethod is a TemplateMethodModelEx.
How about taking a mod of your number, convert it to the required string format and finally add a '-' prefix to the final string. You can retain the default format in just two steps.
Freemarker uses the currency formatting provided by the Java platform.
It requires a little tweaking of the DecimalFormat returned by NumberFormat.getCurrencyInstance() (which is what is called when you call .currency). You can see examples of it here.
However, that said it will likely be more effective for you to create a macro in freemarker to call which will handle your specific formatting.
Sorry for not having an example of what that macro would look like, but it's a good starter into macros in freemarker since you are just learning.
You might investigate if you can supply a custom format using the exposed configuration for number formats that will meet your needs.
If you want to maintain the default currency formatting (in case you need to use a locale other than '$'), you can just replace the parentheses like so:
${transaction.amount?string.currency?replace("(","-")?replace(")","")}
This will work without error regardless of if a number is negative or positive.
TIP: Make sure the number is actually a number with the ?number directive before converting to a currency format

JSTL format String with Mask

is anybody know how to format String with mask using jstl tags? let say you want to show confidential credit card number in list and you just want to show first 4 digit and else will be masked with * something like :
1234-****-****-****
I don't think there is anything out of the box to do this. The fmt namespaced tags are about formatting numbers and dates and i18n stuff, but nothing about string formatting. If you don't want to be doing this in your presentation layer with scriptlets or function invocations, you might want to consider adding another model property for the obfuscated CC number that way you can do the formatting in Java where it will be much easier.

Formatting a BigDecimal in Apache Velocity

In my velocity templates, I've been using the Velocity NumberTool to format number variables as a currency.
Most of these are primitive doubles and they work fine with this tool.
However, some are of type BigDecimal and they don't seem to be formatted at all. It'll just show the expression as is when rendered:
$global.numberTool.currency($someBigDecimalVariable)
Is there a convenient way to format a BigDecimal with Velocity as a currency? What are the alternatives?
Since you can put any object into a Velocity context, the easiest thing to do is to put your own DecimalFormat object in your context and call its format() method in the template.
Of course this isn't a very nice solution but you can refine it to make it more generic.
Can you use JSTL in Velocity? I used the fmt JSTL Tags for displaying BigDecimals as a Currency like this:
<fmt:formatNumber value="${myBigDecimalValue}" type="currency" currencySymbol="€" currencyCode="EUR" minFractionDigits="2" maxFractionDigits="2"/>

Rounding Half Up with Decimal Format in Android

I want to set the Rounding Mode to HALF_UP on my DecimalFormat, but eclipse is telling me that setRoundingMode() is not available on the DecimalFormat class. My project properties (and the overall Eclipse properties) are using the 1.6 compiler. The developer.android.com site says that I can use either Java 5 or 6 so I'm not sure what the problem is.
import java.math.RoundingMode;
import java.text.DecimalFormat;
completedValueFormatter = NumberFormat.getNumberInstance();
DecimalFormat completedDecimalFormat = (DecimalFormat)completedValueFormatter;
completedDecimalFormat.setRoundingMode(RoundingMode.HALF_UP);
I've also tried using the android tools to generate an ant-based project, tried this code in the project and also got the same compile error. So it doesn't appear to be related to Eclipse. It seems related to the Android API.
Any suggestions?
This doesn't truly answer why I can't use the Java 6 .setRoundingMode(RoundingMode) method in DecimalFormat, but it is at least a work-around.
int numDigitsToShow = this.completedValueFormatter.getMaximumFractionDigits();
BigDecimal bigDecimal = new BigDecimal(valueToBeRounded);
BigDecimal roundedBigDecimal = bigDecimal.setScale(numDigitsToShow, RoundingMode.HALF_UP);
return this.completedValueFormatter.format(roundedBigDecimal.doubleValue());
I create a BigDecimal with the value I need to round, then I get a BigDecimal of that value with the scale set to the number of digits I need to round my values to. Then I pass that rounded value off to my original NumberFormat for conversion to String.
If anyone has a better solution, I'm all ears!
Here is what I suspect the problem is, (assuming I am reading the docs properly) and its a doozy:
According to the java.text.DecimalFormat API documentation, you are not actually getting the Runtime Implimentation of the Java 1.6 RE, but are getting an android "Enhanced Version" that clearly doesn't include the setRoundingMode, which frankly bites.
"This is an enhanced version of DecimalFormat that is based on the standard version in the RI. New or changed functionality is labeled NEW."
A weakness in Java for many many many years has been the DecimalFormat class defaulted to HALF_ROUND_UP and had no way to change that, until JVM 1.6. Pity to see Android is keeping this need to kludge alive.
So looks like we are stuck Kludging BigDecimal scale Settings to format output all over any app that needs it, instead of simply being able to rely on a formatter call alone to get the job done. Not the end of the world, but very disappointing Google.
Of course that same doc says that setRondingMode() works, so perhaps this is a all out BUG??
I guess this would be the best option
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#ceil(double)

Conversion of a string to a bigDecimal

My problem is that I have a user input field, which is a textfield, and I have to convert it to a bigDecimal for use at the database.
2,50 --> 2,50
2.50 --> 2,50
2.5 --> 2,50
1200 --> 1200 (or 1200,00)
1.200 --> 1200 (or 1200,00)
1.200,50 --> 1200,50
1,200.50 --> 1200,50
Is there a simple way to convert all these kind of inputs? The use of valueOf or parseDouble does not do the job. I also tried the DecimalFormatter, but I can't find the correct format.
DecimalFormat is the way to go - get the appropriate DecimalFormat for the user's locale, and call setParseBigDecimal(true) so that it parses to BigDecimal rather than double.
Note that you really need to know the right locale - otherwise "1,251" could mean "a bit more than one and a quarter" or "the integer 1251". Admittedly you could try to parse it with every format available and guess which is the right one out of formats that succeed, but that doesn't sound like a great idea to me.

Categories

Resources