For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > October 2005 > Re: [SPAM DETECT] how to get defined number of digits after point of a variable









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: [SPAM DETECT] how to get defined number of digits after point of a variable
Xavier Noria

2005-10-20, 4:00 am

On Oct 20, 2005, at 9:07, Franklin wrote:

> I am a real beginner of perl. after looking for Internet for serveral
> hours, I still can't find the answers for my problem. My question is:
> Which function I can use to get 2 digits after point for a variable?
> For example, for $j=2.56789, how can I get the very first two digits
> after points,ie, I just want to get 2.56.


The usual idioms are printf() and sprintf(), inherited from C:

$j = 2.56789;
printf "%.2f", $j; # -> 2.57

Note that the number has been rounded. Note also we get always two
digits after the dot, even if $j has less:

$j = 3;
printf "%.2f", $j; # -> 3.00

Is that helpful?

-- fxn

PS: See perldoc -f printf, perldoc -f sprintf, and man 3 printf.


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com