develooper Front page | perl.perl5.porters | Postings from January 2012

Re: [perl #107702] Rounding error in sprintf.

Thread Next
From:
Salvatore Domenick Desiano
Date:
January 6, 2012 18:13
Subject:
Re: [perl #107702] Rounding error in sprintf.
Message ID:
CAKnWxp=qVg-R+6QtfQFTKQcFbtFT7AD9WRyPT2NA0NTWnAGqVA@mail.gmail.com
Sam's answer indicates that this is is a result of an efficient
implementation within Perl, which I would argue, using the principle of
least surprise, is a bug if it gives incorrect answers for math that could
be handled within an int. Perhaps a pragma forcing the local implementation
to be used would be a reasonable compromise.

I'm not sure Graham's answer covers it -- program below prints "247", while
perl prints "246", so sprintf isn't behaving the same as the underlying C.

-- Sal
smile.


#include <stdio.h>

int main(void)
{
  float a = 2.47;
  char buf[100];
  sprintf(buf, "%d", int(a * 100));
  printf("%s\n", buf);
  return 0;
}

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About