sprintf & float (was RE: More random python observations from a perl programmer)

Tim Peters tim_one at email.msn.com
Fri Aug 20 01:19:05 EDT 1999


[posted & mailed]

[Tom Christiansen]
> ...
>
> 2. Perl code
>
>     main() {
> 	printf("Float %g rounds to %.0f\n", 1.5, 1.5);
> 	printf("Float %g rounds to %.0f\n", 2.5, 2.5);
> 	printf("Float %g rounds to %.0f\n", 3.5, 3.5);
> 	printf("Float %g rounds to %.0f\n", 4.5, 4.5);
>     }
>     main();  # not called by default
>
>     OUTPUT:
>
> 	Float 1.5 rounds to 2
> 	Float 2.5 rounds to 2
> 	Float 3.5 rounds to 4
> 	Float 4.5 rounds to 4


I know Python (and expect Perl) both inherit their sprintf behavior from the
platform libc.  Here's what Perl does under Windows (& Python does too):

C:\temp>perl temp.pl
Float 1.5 rounds to 2
Float 2.5 rounds to 3
Float 3.5 rounds to 4
Float 4.5 rounds to 5

>>>

Unices also vary widely in what they do to 2.5 and 3.5; I don't know of any
platform that doesn't round 1.5 to 2 and 3.5 to 4, though.

add-a-half-&-chop-is-even-older-than-us<wink>-ly y'rs  - tim






More information about the Python-list mailing list