in reply to (s)printf and rounding woes
If someone should be blamed for this, it is not Perl, but c, and Perl just inherits it. If you are using languages support fixed decimal, for example COBOL or PL/SQL, then this problem disappears.
Here is an example what can happen to c: (It does not give 14720)
#include <stdio.h> void main() { float x = 147.2; printf("%20.20f", x * 100); }
If you really care the accuracy and precision, try Math::BigFloat.
Now here is something a little bit off topic, but interesting. If you do this in c:
float x = 147.2; printf("%d", x * 100);
It produces -167772160, which is ridiculous, as c tries to interprete that piece of memory as integer, as you required.
Good you are using Perl. In Perl, if you do the same thing with:
$x = 147.2; printf("%d", $x * 100);
It produces 14719 (not precise, but better than c), as internally Perl does:
float x = 147.2; printf("%d", (int)(x * 100));
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: (s)printf and rounding woes
by nevyn (Monk) on Nov 05, 2003 at 11:57 UTC |