PDA

View Full Version : Dealing with comma's in numbers (beginner question)


guysml
02-01-2007, 04:01 PM
I am trying to read numbers from a file and do calculations with them. My script works fine EXCEPT when it encounters numbers with commas in them (ie. 1,000,000,000). If $v1 eq "1,000,000,000" and $v2 eq "100" and I subtract $v2 from $v1 I get a result of -99. It would seem that perl is giving $v1 a value of 1 when performing the calculation, and ignoring all the zeros after the first comma.

I have a few ideas how to deal with the situation by removing the commas from all the variables before performing the calculations or something like that. However it would require quite a bit of work (for someone with my limited abilities) to change the script to do this.

Is there an easier way for me to deal with numbers that include commas? I looked through my O'Reilly Learning Perl book, but struggled to find an exact answer. I am really new at this. Any advice/ideas/suggestions would really be appreciated!!!

Thanks,

Guy.

miller
02-01-2007, 06:56 PM
Remove the commas. There is no other way to deal with it.


$number =~ s/,//g;


Yes, you could code a package that would surround all of your arithmetic operations. But that package would have to do the translation as well. And then do you return numbers with commas or without? Gah! Just remove them. The code above will serve that purpose just fine.

FishMonger
02-01-2007, 06:57 PM
http://search.cpan.org/~wrw/Number-Format-1.52/Format.pm