Mise Wonks,

The problem has been encountered many times: print int(2.26*100) = 225 (although print 2.26*100 = 226).

LanX's Humans have too many fingers warns about Floats are not accurate with decimal fractions because the computer "has only two fingers" and offers this advice: calculate with integers in the desired accuracy and shift the decimal point afterwards.

And this is what I was attempting to do: I was converting the float 2.26 into an integer 226 in order to increment it by 1. (Background: 2.26 is a version number and I wanted to bump it up to version 2.27. Since then I discovered Version::Next which can be a solution ...)

In C I get the correct result it seems to me:

# gcc a.c #include <stdio.h> #define ABS(A) ((A)>0?(A):(-(A))) int main(void){ float version = 2.26; float newversion = version + 0.01; printf("version=%f, newversion=%f\n", version, newversion); printf("2.26*100=%.8f\n", 2.26*100); float x = 226.0; if( ABS(x-226.0)>0.00000001 ){ printf("ajaja\n"); } }

And in bc: echo "2.26*100" | bc -l gives 226.00

I have perl v5.36.0 and a modern linux OS on a modern desktop, 64bit, and :

perl -V:nvtype -V:nvsize nvtype='double'; nvsize='8';

So, the advice to use decimal cents to do calculations in cents instead of using floating dollars is sound but how do I get to the decimal cents in the first place?

Oh, wonk: a person preoccupied with arcane details or procedures in a specialized field; broadly : nerd. hehe (Edit: I think "nerd" is superfluous and plain wrong).

bw, bliako


In reply to Yet again: floats are not expressed accurately by bliako

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.