in reply to Different values while applying format specifiers

Thank you all for the insights. But why does it have to work for 10.1, 3.1 and not 5.1, 4.1
printf("%d\n",100 * 3.1); print "10.1 Manipulation\n"; printf("%d\n",100 * 10.1); $c=sprintf("%d\n",100 * 10.1); printf("%.0f\n",100 * 10.1); print $c; print "5.1 Manipulation\n"; printf("%d\n",100 * 5.1); $d=sprintf("%d\n",100 * 5.1); printf("%.0f\n",100 * 5.1); print $d;
This is the output that I see for the above code
310 10.1 Manipulation 1010 1010 1010 5.1 Manipulation 509 510 509

Replies are listed 'Best First'.
Re^2: Different values while applying format specifiers
by kennethk (Abbot) on Aug 26, 2014 at 21:47 UTC
    To explore what the numbers actually look like in memory, print them out with unrealistic precision:
    printf "%.16f\n", 5.1 * 100; printf "%.16f\n", 10.1 * 100; printf "%.16f\n", 20.1 * 100;
    And read that link.

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Re^2: Different values while applying format specifiers
by pme (Monsignor) on Aug 26, 2014 at 22:05 UTC
    Decimal 5.1 is an endless repeating binary number in IEEE-754 format and therefore the value in the memory represents 5.09999999999 in decimal. Accordingly decimal 3.1 is not an endless binary float in the memory.
Re^2: Different values while applying format specifiers
by Anonymous Monk on Aug 27, 2014 at 11:38 UTC
    Just to word pme's response a little more simply: Some decimal numbers can be represented by IEEE-754 exactly, others cannot. For lots more information see the article linked above, or search the Wikipedia page Floating point for the term "exact".