How to create custom money filters in Dot Liquid & C#?

414 Views Asked by At

I am using Dot Liquid to create HTML templates in a C# application. As of now I am displaying numbers to some table cells that I get from a JSON array but I want the numbers to be seperated with a thousands delimiter. For example the number I get from JSON is 40000.50 and I want it to look like this : 40.000,50 with a filter. Unfortunately Dot Liquid's implementation of standard filters is a little bit poor when it comes to customizing numbers. (Also for some reason the money filter does not work in my case). I was wondering if anyone has any idea on how to create a custom filter with C# or if I can somehow use an existing custom filter for my purposes.

1

There are 1 best solutions below

1
Andrii Khomiak On

You can register custom value formatter and pass to it Culture with correct decimal and group separator. Pay attention that value formatter is global and will be applied to all templates.

var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.CurrencyDecimalSeparator = ",";
clone.NumberFormat.CurrencyGroupSeparator = ".";
clone.NumberFormat.CurrencySymbol = "";
Template template = Template.Parse("Format example {{money}}");
Template.RegisterValueTypeTransformer(typeof(decimal), (v) => ((decimal)v).ToString("C", clone));
var result = template.Render(Hash.FromAnonymousObject(new { money = 40000.50m }));

Example: https://dotnetfiddle.net/EpLe1J