Click to See Complete Forum and Search --> : Perl: give me a tip please
-Stalker-
11-13-2000, 08:05 PM
Hello
I have a decimal variable $x=35.2356681, for example.
I need to cut it off to have only two digits after point ($x=35.23), how I could do this?
Thanks before!
commdogg
11-13-2000, 08:29 PM
Is the script for the console or CGI?
If it's for the console use FORMAT:
#!/usr/bin/perl
$float = 12.3456;
write;
format STDOUT =
The variable float equals @##.##
$float
.
I'm semi-new to Perl too, so please don't flame me if I'm wrong. http://www.linuxnewbie.org/ubb/biggrin.gif
------------------
I'm proud to have an X incompatable video card.
Console RULES!
YaRness
11-13-2000, 08:39 PM
Originally posted by -Stalker-:
Hello
I have a decimal variable $x=35.2356681, for example.
I need to cut it off to have only two digits after point ($x=35.23), how I could do this?
Thanks before!
look up the printf/sprintf commands in the perlfunc man page. i don't have it handy, but i know there's a way to format the number of decimal places.
------------------
"Assembly of Japanese bicycle require great peace of mind."
Registered Linux User #188285 http://counter.li.org/
------------------
klamath
11-13-2000, 10:00 PM
What not use a regex? e.g.
$x =~ m[^(\d+\.\d\d)];
$new_x = $1;
------------------
- Klamath
Get my GnuPG Key Here (http://klamath.dyndns.org/mykey.asc)
Looking for an open source project to contribute to? Check out the BBB (http://bbb.sourceforge.net)
takshaka
11-13-2000, 10:50 PM
I assume by your example that you only want to truncate, not round, the number to 2 decimal places. I like this approach:
$x = int($x*100)/100;
If you do want to round, use sprintf...
$x = sprintf "%.2f", $x;
YaRness
11-14-2000, 09:26 AM
Originally posted by klamath:
What not use a regex? e.g.
$x =~ m[^(\d+\.\d\d)];
$new_x = $1;
i was trying to think up something like that last night, but what about if you happen to get one with one decimal place, or none...
also i've had it highly recommended to use control structure in combination with back referencing to make sure what you are referin to is what you intended.
------------------
"Assembly of Japanese bicycle require great peace of mind."
Registered Linux User #188285 http://counter.li.org/
------------------