[Israel.pm] floating point curiosity

Peter Gordon peter at pg-consultants.com
Wed Jan 4 04:52:27 PST 2006


Floats don't get stored exactly. They may be out by a little bit in
either direction. 

So 512.05 might get stored as 512.049999999999999
Multiply by 1000 and you get 512049.9999999
int truncates, so you get 512049.

What you need to do is int($float*1000 + 0.5) or 
sprintf("%.f",$float*1000) 

Peter

On Wed, 2006-01-04 at 14:32 +0200, Levenglick Dov-RM07994 wrote:
> Hi,
> Can someone please explain what is happening here?
> 
> #!/usr/local/bin/perl5.6.1
> $float1 = 16.05;
> $float2 = 32.05;
> $float3 = 512.05;
> print $float1, " ", $float1*1000, " ", int ($float1*1000), "\n";
> print $float2, " ", $float2*1000, " ", int ($float2*1000), "\n";
> print $float3, " ", $float3*1000, " ", int ($float3*1000), "\n";
> 
> Produces:
> 16.05 16050 16050
> 32.05 32050 32049
> 512.05 512050 512049
> 
> The question has to last printed value.
> 
>  
> Best Regards,
> Dov Levenglick
> DSP SoC System and Applications Engineer,
> Network and Computing Systems Group
> Freescale Semiconductor Israel
> Tel. +972-9-952-2804
> The information contained in this email is classified as:
> [ ] General Business Information
> [ ] Freescale Internal Use Only
> [ ] Freescale Confidential Propriety
> [x] Personal Memorandum
>  
> 
> 
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
> 
> 





More information about the Perl mailing list