Xho Jingleheimerschmidt wrote:
> John Bokma wrote:
>> kevin0051 <> writes:
>>
>>> I made a perl program as follows.
>>>
>>> -----------------
>>> $AAA = 4.31;
>>> $AAA *= 100;
>>> printf ("%f\n", $AAA);
>>> printf ("%d\n", $AAA);
>>> ----------------
>>>
>>> The output of this program is
>>> 431.000000
>>> 430
>>>
>>> I don't know why the second output is 430 instead of 431.
>>> Can anyone help?
>>
>> http://en.wikipedia.org/wiki/Floatin...uracy_problems
>>
>
> This surprised me. I knew int() would truncate of course, but I thought
> printf with would round in the same way for %d as it does for %.0f,
> rather than truncate.
>
It shouldn't surprise you:
perl -e '$f = 4.31; $f *= 100; $h[$f] = 0; print $#h'
430
I would expect any use of a scalar as an integer to truncate.
Similarly:
perl -e '$f = "430plusalittle"; printf "%d",$f'
430
Using a string as an int stops at the first non-digit.
It should not take any of the rest of the string into account.
In the same way, %d should ignore any part of a float other than
the integer part.