Search code examples
perlcpantemplate-toolkit

Perl how to drop decimal points if 00


I have a string being generated passed to and outputed by template toolkit using:

https://metacpan.org/module/Template::Plugin::Number::Format

Its using format_price I want to drop the cents off the price if they are zero. So 100.00 becomes 100

Can't find any clear solution to this.

Update:

format_price is used in hundreds of places within this project and if possible i'd like to not change that and override the method with this functionality if possible.


Solution

  • You can extend Template::Plugin::Number::Format to create your own plugin like so:

    package Template::Plugin::My::Number::Format;
    use base qw(Template::Plugin::Number::Format);
    use Number::Format;
    
    sub init {
        my ($self, $config) = @_;
        $self->SUPER::init($config);
        my $nfo = Number::Format->new(%$config);
        $self->{ _CONTEXT }->define_filter(format_price => sub {
            my ($context, @args) = @_;
            return sub {
                my $text = shift;
                my $result = $nfo->format_price($text, @args);
                $result =~ s/\.00$//;
                return $result;
            };
        }, 1);
        return $self;
    }
    

    Then inside your templates you would use your plugin like so:

    [% USE My.Number.Format %]
    ...
    [% some_number | format_price %]