Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am having problems adding and multiplying numbers that have decimals in the. 1.25 + 805.75 or 64 * 35.55. I am adding numbers together in a shopping cart and it's removing the decimals when I add or multiply them.

How can I fix this?

Replies are listed 'Best First'.
Re: math with decimals
by ikegami (Patriarch) on Nov 24, 2005 at 00:47 UTC

    Do you mean it doesn't display trailing zeroes in the decimals? You can add them using sprintf:

    $num = 64; $num = sprintf('%.2f', $num); print($num, "\n"); # Prints 64.00

    Note that %f rounds:

    $num = 123.456; $num = sprintf('%.2f', $num); print($num, "\n"); # Prints 123.46

      or just use printf:

      printf "%.2f %.2f\n", 1.25 + 805.75, 64 * 35.55;

      Prints:

      807.00 2275.20

      DWIM is Perl's answer to Gödel
Re: math with decimals
by GrandFather (Saint) on Nov 24, 2005 at 00:48 UTC
    use strict; print (1.25 + 805.75 . ' ' . 64 * 35.55);

    Prints:

    807 2275.2

    Where's the problem?


    DWIM is Perl's answer to Gödel
Re: math with decimals
by saintmike (Vicar) on Nov 24, 2005 at 02:27 UTC