On Wed, Jan 14, 2009 at 14:02, Rob Dixon <rob.di...@gmx.com> wrote:
> Gunnar Hjalmarsson wrote:
>> ANJAN PURKAYASTHA answered:
>>> ANJAN PURKAYASTHA asked:
>>>>
>>>> I would like to divide a floating point number into its whole and 
>>>> fractional
>>>> parts.
>>>> So,
>>>> ($w, $f)= some_subroutine(12.735)
>>>> assigns 12 to $w and 0.735 to $f.
>>>>
>>>> Any easy perlish way of doing this?
>>> after some research i was able to answer my own question.
>>> solution:
>>>
>>> use POSIX;
>>> $n= 12.735;
>>>
>>> $w= floor($n); # assigns the value 12 to $n.
>>>
>>> $f= $n-$w; # this holds the fractional value.
>>
>> print $f outputs 0.734999999999999 on my box.
>>
>> Owen's solution does not have that problem.
>>
>
> Owen wrote:
>>
>> #!/usr/bin/perl -w
>>
>> use strict;
>>
>> my $nr = "12.75";
>>
>> my ( $whole, $part ) = ( int($nr), $nr - int($nr) );
>>
>> print "$whole   $part\n ";
>
> Owen's solution doesn't show the problem because he uses a value of 12.75, 
> which
> is exactly representable in binary, rather than 12.735, which is a recurring
> binary value.

The only way to stop that is to use non-floating point numbers, or to
round the results.  I believe Perl does rounding for you when it
converts a number to a string, so you should be able to say

my ($whole, $part) = split /\./, 7.735;

$part will be equal to 735 in this case.  It might not always work
though.  If you need exact representations of numbers you will need to
use something other than floating point representations.  A quick
search of CPAN turns up Math::FixedPrecision*.

* http://search.cpan.org/dist/Math-FixedPrecision/FixedPrecision.pm

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to