Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re^4: How to use the int-function?

by Anonymous Monk
on Jan 03, 2011 at 15:53 UTC ( #880213=note: print w/replies, xml ) Need Help??

in reply to Re^3: How to use the int-function?
in thread How to use the int-function?

kennethk, I've not yet found that printf would help me with formatting the output:

perl -e 'printf("%.2f\n", 1.255)'

-> 1.25

perl -e 'printf("%.2f\n", 1.455)'

-> 1.46

Although, there might be some option which jumps into the gap and helps to round the number?

Replies are listed 'Best First'.
Re^5: How to use the int-function?
by kennethk (Abbot) on Jan 03, 2011 at 16:07 UTC
    Because the double precision approximation of 1.255 is slightly below 1.255 and the double precision approximation of 1.455 is slightly above 1.455. You introduce the error during the assignment, not during the manipulation. Ratazong's solution actually introduces additional errors into the process since now you have two approximated numbers, as well as additional maintenance complexity.

    Why is your application so sensitive to this change? There are ways to handle it, but this is a consequence of the real hardware you are working with. Depending on your application, you could do all your math with integers, use Math::BigFloat, use Math::BigRat, or tweak your algorithm/order of operations.

      Thanks, kennethk, I really think you have shed some light on the problem, and I see much clearer now.

      To close my contribution so far, its not that I am stuck with my application, but I was puzzled to not get the most basic arithmetic under my control using a powerful computing device. But as you showed me, its not as easy as "want" to come to the "getter".

Re^5: How to use the int-function?
by ruzam (Curate) on Jan 03, 2011 at 19:30 UTC

    If you're going to use printf to round then you have to be aware that it uses the Round half to even method of rounding. I've been bit by that before.

    perl -e 'foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) { printf("$i -> %.0f\n", $i) }'
    0.5 -> 0 1.5 -> 2 2.5 -> 2 3.5 -> 4

    Without resorting to another module to round for you, you probably want use int() something like this (being careful to adjust the rounding value to match your circumstances).

    perl -e 'foreach my $i ( 1.155, 1.255, 1.355, 1.455 ) { print $i, " -> " , int($i * 100 + 0.5001)/100 . "\n" }'
    1.155 -> 1.16 1.255 -> 1.26 1.355 -> 1.36 1.455 -> 1.46

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2020-11-26 13:14 GMT
Find Nodes?
    Voting Booth?

    No recent polls found