Tyraziel has asked for the wisdom of the Perl Monks concerning the following question:

I have been playing around with Template::Toolkit for some time now and I have run into the need of currency formatting. I currently have a commafy display function (the code for that I found here :-D) that I am using in my Template and I tried using the format filters that come with Template::Toolkit to add decimal places to the number, but it appears that it only effects the output.

It would be ideal to have a solution that I can format the number and then commafy it via Template::Toolkit and not have to inject perl code (which I'm doing now via sprintf.) I have a couple of ideas on how to do this and I am seeking wisdom on the best approach.

  1. I could add another function to my display module that will take care of adding decimal places to my number. In my template I would call the decimal format function first and then the commafy function to get the desired output.
  2. I could create a new function that commafys and formats the number, but just because I'm adding decimal places I might not want to commafy and just because I want to commafy a number doesn't mean that I want to add decimal places.
  3. I could format the number in my template driver module and I wouldn't have to worry about formatting in my template, but I know that the template is where formatting of data should occur, so this option isn't my most ideal solution.

Any suggestions on how to get this done the right and correct way would be greatly appreciated. Thank you for your time.

  • Comment on Template Toolkit Formatting Data Question (sprintf and commafy)

Replies are listed 'Best First'.
Re: Template Toolkit Formatting Data Question (sprintf and commafy)
by jeffa (Bishop) on Jul 13, 2005 at 14:57 UTC

    I'm a bit confused as to what your problem is. Did you try something like this?

    use strict; use warnings; use Template; my $tt = Template->new({ FILTERS => { commify => \&commify, }, }); $tt->process(\*DATA, { number => 420000.2527 }) || die $tt->error(); # Perl Cookbook recipe 2.17 sub commify { my $text = reverse $_[0]; $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $text; } __DATA__ [% number | format('%.02f') | commify %]
    This command line script simply creates a custom filter to commify, and uses the built in format filter to truncate the extraneous decimal numbers. This way, you can use number as it is, or chain it to get a combination of commify and sprintf.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      jeffa,

      Thank you for your help. Your solution works great!

      I opted to see if I could expand the MACRO provided in the POD - worked well enough for my need but ymmv:
      [%- MACRO commify(n) GET n.replace('\.\d+$','').chunk(-3).join(',') _ +n.replace('^\d+', '') %]