in reply to sprintf values

Mixing integers and floating point is always problematic, the following illustrates:
use strict; use warnings; my @num = (3.95,4.95,5.95,8.95,8.94,8.96,9.95,9.96,9.97,9.94,10.08); foreach (@num){ my $num = $_ *100; printf ("%d\t%010d\t%011.4f\n", $num, $num, $num); } 395 0000000395 000395.0000 495 0000000495 000495.0000 595 0000000595 000595.0000 894 0000000894 000895.0000 894 0000000894 000894.0000 896 0000000896 000896.0000 994 0000000994 000995.0000 996 0000000996 000996.0000 997 0000000997 000997.0000 994 0000000994 000994.0000 1008 0000001008 001008.0000

Update: I just noticed I got slightly different results to you, which only goes to show how untrustworthy conversions are. I am probably running on different hardware, operating system, perl version, and C runtime library to you.

Replies are listed 'Best First'.
Re^2: sprintf values
by almut (Canon) on Apr 07, 2010 at 15:41 UTC
    ...and C runtime library

    FWIW, the C runtime library shouldn't matter here, as Perl has its own "printf"-like formatting routine ( Perl_sv_vcatpvfn() in sv.c, in case you're interested ).

      I think sv_vcatpvfn can or does use the C runtime to format floats. Even if it doesn't, the C runtime is used to create the floats in the first place, so it definitely matters.

        I just re-checked with ltrace, and yes you're right, it does in fact call snprintf() and frexp() to format floats.

        I had done a similar check some time ago, and was surprised to not find any libc calls related to Perl's s/printf()  (which is why I posted) — but that must have been without a float format specifier being used... (rather only integer formatting like %d, %u etc.)   As to the creation of floats, however, I don't see any calls to libc or libm. Any idea what function that would be (just out of curiosity)?