#!/usr/bin/perl use strict; use warnings; my $n1 = 35.152000; my $n2 = 35.152001; my $tol = 1; if(doTest($n1,$n2,$tol)){ print "Strings are the same\n"; } else { print "Strings are not the same\n"; } exit(0); sub doTest { my($n1,$n2,$tol) = @_; $n1 =~ /(\d*)\.?(\d*)/; my ($intPart1,$fracPart1) = ($1,$2); $n2 =~ /(\d*)\.?(\d*)/; my ($intPart2,$fracPart2) = ($1,$2); my $numSigFigs1; my $numSigFigs2; if($fracPart1 ne ''){ $numSigFigs1 = -length($fracPart1); if($fracPart2 ne ''){ $numSigFigs2 = -length($fracPart2); } else { $numSigFigs2 = 0; } } else { $numSigFigs1 = 0; if($fracPart2 ne ''){ $numSigFigs2 = -length($fracPart2); } else { $numSigFigs2 = 0; } } # ensure that the highest precision number controls whose'last digit' we # are comparing my $sigFigs = $numSigFigs1; $sigFigs = $numSigFigs2 if($numSigFigs2 < $numSigFigs1); my $test = $tol * 10**($sigFigs); # use the sprintf() function to be sure that there aren;t any stray diits # way out beyond the number o significant figures you're interested in # that interfere with the test using abs($n1-$n2) <= $test. if(sprintf("%.*f",abs($sigFigs),abs($n1 - $n2)) <= $test){ return 1; # strings are the same within tolrance $tol } else { return 0; # strings are not the same within tolerance $tol } } # end sub doTest()