Skip to content

Commit

Permalink
add money filter
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Skjølberg <[email protected]>
  • Loading branch information
Lyosha Kuleshov authored and skjolber committed Aug 11, 2016
1 parent 3a3f3d1 commit 487f6e4
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/main/java/liqp/filters/Filter.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public abstract class Filter extends LValue {
registerFilter(new liqp.filters.Map());
registerFilter(new Minus());
registerFilter(new Modulo());
registerFilter(new Money());
registerFilter(new Newline_To_Br());
registerFilter(new Plus());
registerFilter(new Prepend());
Expand Down
39 changes: 39 additions & 0 deletions src/main/java/liqp/filters/Money.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package liqp.filters;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Money extends Filter {

/*
* money(input)
*
* Attempts to format a string containing numeric values as currency.
*/
@Override
public Object apply(Object value, Object... params) {

String val = super.asString(value);
String res;
Pattern r = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher m = r.matcher(val);

if (m.find()) {
BigDecimal n = new BigDecimal(m.group(2));
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);
res = m.group(1) + formatter.format(n.longValue()) + m.group(3);
} else {
res = super.asString(val);
}

return res;
}
}
31 changes: 31 additions & 0 deletions src/test/java/liqp/filters/MoneyTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package liqp.filters;

import liqp.Template;
import org.antlr.runtime.RecognitionException;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class MoneyTest {

@Test
public void applyTest() throws RecognitionException {

String[][] tests = {
{"{{ '1000 $' | money }}", "1 000 $"},
{"{{ '£20000' | money }}", "£20 000"},
{"{{ 200 | money}}", "200"},
{"{{ 'Amazing! 1500.50 eur' | money}}", "Amazing! 1 500.50 eur"},
{"{{ 'wut' | money }}", "wut"},
};

for (String[] test : tests) {

Template template = Template.parse(test[0]);
String rendered = String.valueOf(template.render());

assertThat(rendered, is(test[1]));
}
}
}

0 comments on commit 487f6e4

Please sign in to comment.