Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: perl floating number addition

by biohisham (Priest)
on Jul 18, 2009 at 12:23 UTC ( #781318=note: print w/ replies, xml ) Need Help??


in reply to perl floating number addition

it seems like you want to restrict yourself to 2 digits after the point. Hence instead of print,you use "printf or sprintf" functions in the type of notation you want, in this case the "f" for floating numbers preceded by the digit capacity, that is 3 digits before the point and two digits after the point, preceded by %, so it would look like this printf "%6.2f", notice, the point is included in the count hence 6.2 instead of 5.2(Updated after Albannach reply)

$count = 895.3; while ($count <= 899.99) { $count += 0.01; printf "%6.2f",$count; #(updated) print "\n"; }
the numbers in computers are approximations and hence comes such issues esp while using higher level programming languages such as Perl.
Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind


Comment on Re: perl floating number addition
Download Code
Re^2: perl floating number addition
by Albannach (Prior) on Jul 18, 2009 at 13:49 UTC
    A (pretty common) nit to pick here: the 3 in %3.2f is not the number of digits before the decimal, it's the minimum total width of the resulting field, including the decimal. So if you really want 3 digits, a decimal and 2 digits, then you need %6.2f. This is a minimum and the digits to the left of the decimal will still be printed, so your example of 895.3 still appears to work (even though it would be better described as %5.1f), but try that in a table and you'll find that the column won't line up when another value is just 1.23 for instance.

    For illustration, printf("%3.2f\n",$_) for (3.2,32.2,322.2) gives:

    3.20 32.20 322.20

    while printf("%6.2f\n",$_) for (3.2,32.2,322.2) gives:

    3.20 32.20 322.20

    --
    I'd like to be able to assign to an luser

      Thanks buddy for this, I will have it rectified, when I saw the start of your reply and I was like aoooo I mixed up some other coordinates system from another utility. Thanks, I admit I fell for the trap, I will make an update.
      Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://781318]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2014-12-22 06:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (111 votes), past polls