Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Calculations with formatted numbers

by fglock (Vicar)
on Feb 15, 2005 at 17:47 UTC ( [id://431272]=note: print w/replies, xml ) Need Help??


in reply to Calculations with formatted numbers

Here is the "magic" answer:

package Number::Formatted; use Number::Format; my $format = new Number::Format ( thousands_sep => '.', decimal_point => ',' ); use overload '""' => sub { $format->format_number( ${$_[0]} ) }, '+' => sub { my $num = ref( $_[1] ) ? ${$_[1]} : $_[1]; $num = ${$_[0]} + $num; return bless \$num, Number::Formatted; }, fallback => 1; sub new { my $num = $format->unformat_number( $_[1] ); return bless \$num, $_[0]; } package main; my $n = new Number::Formatted ( '1.234,56' ); my $m = new Number::Formatted ( '123,45' ); print $n, "\n"; print $n + 10, "\n"; print $n + $m, "\n"; # 1.234,56 # 1.244,56 # 1.358,01

Replies are listed 'Best First'.
Re^2: Calculations with formatted numbers
by holli (Abbot) on Feb 16, 2005 at 10:17 UTC
    Thank you! Exactly what i was looking for!

    So i created similar overloads for the other operators (-, *, /, **) that work fine.

    But these do not:
    #... '++' => sub { $num = ${$_[0]} + 1; return bless \$num, Number::Formatted; }, '--' => sub { $num = ${$_[0]} - 1; return bless \$num, Number::Formatted; },
    Any idea why?


    holli, /regexed monk/

      ++ and -- are mutators - see perldoc overload. This is how to implement them:

      package Number::Formatted; use Number::Format; my $format = new Number::Format ( thousands_sep => '.', decimal_point => ',' ); use overload '""' => sub { $format->format_number( ${$_[0]} ) }, '+' => sub { my $num = ref( $_[1] ) ? ${$_[1]} : $_[1]; $num = ${$_[0]} + $num; $num = - $num if $_[2]; return bless \$num, Number::Formatted; }, '-' => sub { my $num = ref( $_[1] ) ? ${$_[1]} : $_[1]; $num = ${$_[0]} - $num; $num = - $num if $_[2]; return bless \$num, Number::Formatted; }, '++' => sub { ++ ${$_[0]}; shift }, '--' => sub { -- ${$_[0]}; shift }, ; sub new { my $num = $format->unformat_number( $_[1] ); return bless \$num, $_[0]; } package main; my $n = new Number::Formatted ( '1.234,56' ); my $m = new Number::Formatted ( '123,45' ); print $n, "\n"; print $n + 10, "\n"; print $n + $m, "\n"; print $n - $m, "\n"; print ++$n, "\n"; # 1.234,56 # 1.244,56 # 1.358,01 # 1.111,11 # 1.235,56

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://431272]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 12:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found