Forum Moderators: coopster & phranque

Message Too Old, No Replies

Perl Decimals

Too many decimal places

         

mdharrold

1:45 am on May 9, 2001 (gmt 0)

10+ Year Member



I have been learning PERL the past few monthes with no problems until now. I have a survey script that builds a bar graph based on responses. When I convert the response totals to percentages, there are 13 decimal places. I would like to limit it to 2 decimal places. I have read everything I can find and have not found the fix. If it matters, I am using the <<endhtml thingy.

Edited by: mdharrold

theperlyking

1:46 am on May 9, 2001 (gmt 0)

10+ Year Member



Welcome to WmW mdharrold.
I'm not sure what the correct way to do this actually is but this is what I do:
- multiply the number by 100
- take the integer of the result
- divide again by 100.
The code would look something like this:
$percent=int(((100/$total)*$value))*100;
Ok, maybe theres a few too many brackets in there but I confuse easy :)

mdharrold

2:00 am on May 9, 2001 (gmt 0)

10+ Year Member



You fixed it. It now only shows the whole number and no decimals which is fine by me. Thank you.

By the way, where is the best place for PERL tutorals without a bunch of programmer mumbo-jumbo language?

theperlyking

2:11 am on May 9, 2001 (gmt 0)

10+ Year Member



heh, not sure it was supposed to do that but i'm sleepy :)

Not free but I found that picking up a copy of O'Reilly's "learning perl" book was very useful - I think it cost £15 which whilst not an insignificant amount has paid for itself many many times over.

Brett_Tabke

9:47 pm on May 9, 2001 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



The O'Reilly perl series is excellent - get the camel.
[oreilly.com...]

theperlyking

10:04 pm on May 9, 2001 (gmt 0)

10+ Year Member



I have the camel too, in fact its a little like a zoo in here - its impressive how consistently good O'Reilly books are.

sugarkane

10:16 pm on May 9, 2001 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



>I would like to limit it to 2 decimal places

A rather slinky way of doing it is:

$number =~s/(^\d{1,}\.\d{2})(.*$)/$1/;

where $number is the result with too many decimal places.

The \d{2} part controls how many decimal places you want - in this case 2. It doesn't do rounding - just chops off any decimal places you don't want.

>how consistently good O'Reilly books are.

Agreed - I'm a big fan of the 'nutshell' book as well for a quick reference.