How to customize number format in freemarker? - java

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

Related

How do I automatically format all numbers based on the current locale in Android?

I am aware of
NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
But I want all the numbers shown in my app to be formatted according to the locale, thus I don't think it will be a good way to format them one by one using the above method.
So is there some global setting/variable/configuration that I have to change in order to do that?
Locale-aware formatting requires more than just translating e.g. month names from one language to another. In Java that's handled by separate classes apart from the ones that actually hold the values, e.g. NumberFormat, DateFormat. So there's no way around using them like you already do.
What you could try is to create some wrappers or convenience methods (like formatDate(Date)) to simplify things for you. Also put format strings into Android Resources (res/values).

Android studio strange warning

I'm new to code in Android Studio and when i set a integer in a text like this:
textview.setText(String.format("%d",1));
This code give me back a warning:
Implicitly using the default locale is a common source of bugs: Use String.format (Locale,...)
What is the correct code for put an integer in a .setText?
I founded more question on stackoverflow but don't apply to this.
What is the correct code for put an integer in a .setText?
You simply need to convert your int as a String, you can use Integer.toString(int) for this purpose.
Your code should then be:
textview.setText(Integer.toString(myInt));
If you want to set a fixed value simply use the corresponding String literal.
So here your code could simply be:
textview.setText("1");
You get this warning because String.format(String format, Object... args) will use the default locale for your instance of the Java Virtual Machine which could cause behavior change according to the chosen format since you could end up with a format locale dependent.
For example if you simply add a comma in your format to include the grouping characters, the result is now locale dependent as you can see in this example:
System.out.println(String.format(Locale.FRANCE, "10000 for FR is %,d", 10_000));
System.out.println(String.format(Locale.US, "10000 for US is %,d", 10_000));
Output:
10000 for FR is 10 000
10000 for US is 10,000

how to use cell.getArabicOption(int arabicoption)

i don't know what the integer can i use it in this function
so i have a problem to show arabic in my creating pdf
i use iText library to get this function
if some on know how to use it please inform me
You shouldn't use int values such as 0, 1, 2,... in your code as it will be very hard for people to know what these values mean (just like you currently have no idea which options are available).
Instead you should use constants that are provided by iText. The API documentation informs you that the parameters for the setArabicOptions() method can be a combination of:
ColumnText.AR_NOVOWEL: Eliminate the arabic vowels,
ColumnText.AR_COMPOSEDTASHKEEL: Compose the tashkeel in the ligatures, or
ColumnText.AR_LIG: Do some extra double ligatures.
If you want to know which exact int values correspond with these constants, you can always print them out or look inside the code, but there is no reason to do this.
The different values are actually to be used as flags (or bits). You can combine these values like this:
column.setArabicOptions(
ColumnText.AR_NOVOWEL |
ColumnText.AR_COMPOSEDTASHKEEL |
ColumnText.AR_LIG);

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.

Java Unit conversion

I have a database table which stores the units name in full like liters, kilograms, milliliters, milligrams etc.. I need a library to recogonize these units and convert it to the unit I wish to. How do i do this ?
Code Logic:
I will read the unit "liters" from database and i wish to convert it to milli-liters so her the input is "20 liters" and output should be "20000 milli-liters"
I downloaded JScience library but i am not sure how to do this. please tel me how to use that or suggest any alternative. It would be better if you explain me with a code sample. Thanks!!
I'm inclined to say use Frink, but it does WAY more than you need here, although it does solve the problem
20 litres -> milliliters
//gives 20000
And it is just a cool little language. In java you'd have to run it like any other scripting library. The website has loads of info
I'm not aware that JScience provides a facility for parsing strings like "20 liters" (that spelling makes me cringe...), so you'll probably have to handle that yourself, by tokenizing the string into quantities and units.
Once you have that, you can use JScience to convert between units easily enough, although obviously converting from litres to milliltres is trivial. But in principle, it's something like:
Measure<Integer, Volume> input = Measure.valueOf(20, NonSI.LITRE);
Measure<Integer, Volume> output = input.to(SI.MILLI(NonSI.LITRE));
System.out.println(output);

Categories

Resources