There are a couple of points to be wary of in any processing like this. One is that floating point numbers are not equivalent to rational numbers. Some results will look something like

$x = 75; $y = sprintf("%1.15f", 75/5); print $y; # 14.999999 ($i, $f) = split(/\./, $y); print "Integer part: $i\nFractional part: $f\n"; # Integer part 14 # Fractional part 0.999999

Note:  this is an example, not necessarily an actual result.


Which is, of course, right, and is also, probably, useless. (I'm currently ignoring the bignum pragma).

What I would tend to do would be something like this:


As an example:
#!perl use strict;use warnings; my $fmt = "%1.5f"; # set 5 decimal places while(<DATA>){ chomp; (my $dividend, my $divisor) = split(/\s+/,$_,2); (my $int, my $frac) = split(/\./, (sprintf($fmt, ($dividend/$div +isor))),2); print "Integer part: $int\tFractional part: $frac\n"; } __DATA__ 1 2 2 1 3 4 4 3 127 5 75 5

Produces:

Integer part: 0 Fractional part: 50000
Integer part: 2 Fractional part: 00000
Integer part: 0 Fractional part: 75000
Integer part: 1 Fractional part: 33333
Integer part: 25        Fractional part: 40000
Integer part: 15        Fractional part: 00000

The other possible 'gotchas' include the possibility that results may not be consistent between platforms or between Perls built with different compilers on the same platform. Floating point arithmetic is fraught with peril.

emc

Experience is a hard teacher because she gives the test first, the lesson afterwards.

Vernon Sanders Law

In reply to Re: grep integer and fractional part from a division (modulus ?) by swampyankee
in thread grep integer and fractional part from a division (modulus ?) by jeanluca

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.