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

Removing comma's from int (numbers)

by Anonymous Monk
on Jun 12, 2013 at 22:12 UTC ( [id://1038601]=perlquestion: print w/replies, xml ) Need Help??

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

I am helping someone out. They allow someone to request a payout amount from their commissions.

They use a form to submit the amount.

currently they do this:

my $grossAmt = param("amt"); if($grossAmt =~ /\,/) { $grossAmt =~ s/\,//g; $grossAmt = sprintf('%.2f', $grossAmt); }
Besides doing some other sanitization to make sure it is a dollar amount and no code...

anyhow my question is this. Is that the best way to do it? Or is there a single string that will do the whole thing, without them having to do all of that?

Thanks,
Rich

Replies are listed 'Best First'.
Re: Removing comma's from int (numbers)
by choroba (Cardinal) on Jun 12, 2013 at 22:16 UTC
    You do not have to backslash a comma, it has no special meaning in a regexp. Also, you can fire the substitution right ahead without testing it will succeed - if it does not, nothing happens.
    my $grossAmt = param("amt"); if ($grossAmt =~ s/,//g) { $grossAmt = sprintf '%.2f', $grossAmt; }

    Are you sure you want to format the number only if commas were removed?

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Removing comma's from int (numbers)
by farang (Chaplain) on Jun 13, 2013 at 07:30 UTC

    The transliteration (tr) operator could also be used here to avoid the full overhead of regular expressions.

    use strict; use warnings; my $grossAmt = "12,345,678.9"; $grossAmt =~ tr/,//d; $grossAmt = sprintf('%.2f', $grossAmt); print $grossAmt, $/; __END__ output: 12345678.90

Re: Removing comma's from int (numbers)
by LanX (Saint) on Jun 12, 2013 at 22:24 UTC
    If I get you right, the problem lies in the habit to use ',' as thousand separator, like in 1,234,567.99.

    Perl nows _ as such a separator, so s/,/_/g should already solves the issue.

    UPDATE

    Sorry, further tests showed that this doesn't work in strings only for literal numbers.

    Just stick with s/,//g

    DB<123> $x="1,234,567.99" => "1,234,567.99" DB<124> $x =~ s/,//g => 2 DB<125> sprintf('%.2f', $x); => "1234567.99"

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-03-28 18:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found