read float from string and approximation problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bimbam
    New Member
    • Aug 2007
    • 19

    #1

    read float from string and approximation problem

    Hi,

    I try to read a float in a string using sscanf or atof. It seems to work but then it's a bit strange when I manipulate the value obtained.

    Code:
    float fl;
    char  str[]="1.43"
    
    fl=atof(str);
    
    printf("%f\n",floor(1000.0*fl) );
    These lines return : 1429.000000

    It seems to be due to the precision of the float type (Isn't it?).
    Do you know how I can avoid that?

    Regards
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    What every computer scientist should know about floating-point arithmetic.

    kind regards,

    Jos

    Comment

    • MACKTEK
      New Member
      • Mar 2008
      • 40

      #3
      First I want to thankyou, I had not seen the floor() function before.

      Perhaps you are looking for how to format your output?

      Try changing your line as follows:
      printf("%.2f\n" ,(floor(1000.0* fl)) );

      The %.2f tells the printf you want 2 places to the right of the decimal.

      There's a whole bunch more on how to format your output here.
      Last edited by MACKTEK; Mar 9 '08, 04:18 AM. Reason: spelling

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Originally posted by bimbam
        These lines return : 1429.000000

        It seems to be due to the precision of the float type (Isn't it?).
        Do you know how I can avoid that?
        Avoid what? you have not actually stated what you find undesirable about this output, the code is working correctly.

        Comment

        Working...