Hello,
The function sprintf does the rounding automatically. You don't need to add the 0.005.
From the sprintf manual:
f,F The double argument is rounded and
converted to decimal notation in the style -ddd.ddd,
where the number of digits after the decimal-point
character is equal to the precision specification.
Doing a small test reveals the same behavior in perl:
#!/usr/bin/perl -w
print `cat $0`;
for $i (1..10){
my $num = 0;
for(1..9800*$i){
$num += 0.0001/$i;
}
print "$num = ";
$num = sprintf("%.4f", $num);
print "$num\n";
}
0.979999999999908 = 0.9800
0.9799999999999 = 0.9800
0.979999999999902 = 0.9800
0.980000000000962 = 0.9800
0.980000000000699 = 0.9800
0.979999999999897 = 0.9800
0.980000000000605 = 0.9800
0.979999999999383 = 0.9800
0.979999999998648 = 0.9800
0.979999999998175 = 0.9800
Aziz,,,
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|