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

If you are going to be formatting a number for output, I would suggest you use the methods designed specifically to handle that - printf and sprintf. If you are rounding/truncating a value in the context of numerical manipulation, then the approach you take very much depends on your specific needs. There is a very rich field of academic study revolving around performing computations with discrete approximations.

#!/usr/bin/perl use strict; use warnings; my $i = 1.255; my $j = $i * 100 + 0.5; $j *= 10000000; printf "%.0f\n", $j;

outputs

1260000000

Replies are listed 'Best First'.
Re^4: How to use the int-function?
by Anonymous Monk on Jan 03, 2011 at 15:53 UTC
    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?

      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".

      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