255/1000 is a periodic number in binary just like 1/3 is a periodic number in decimal. It would take infinite storage to store it as a floating point number, so it is stored approximately.
$ perl -e'printf "%.20e\n", 1.255'
1.25499999999999989342e+00
$ perl -e'printf "%.20e\n", (1.255 * 100 + 0.5) * 10000000'
1.25999999999999976158e+09
Is there a way to make perl behave as a humble user of arithmetics would have expected
No. If you're using floats, there's no way to make both of these true since the input is the same:
int(1259999999.999999) = 1259999999
int((1.255 * 100 + 0.5) * 10000000) = 1256000000
Said humble user will be disappointed in one of the two cases. But maybe you're ok with the user being disappointed in the former case. Just apply a bit of rounding at the desired tolerance.
( $j = sprintf("%.6f", $j) ) =~ s/\..*//s;
-
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.
|