Thread: Precision with floats

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    25

    Precision with floats

    I'm using fscanf to input floats from a file, how do I specify the number of decimal places I want read? The inputs are things like "123.456" and not "123.4560000" (or, as sometimes happens, "123.459999".

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You could round the number after it has been read. I don't think scanf() supports printf()'s %.2f modifier.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    Ahh, OK. How do I round, then? The round functions I've found round it to the nearest integer. Is there an easier way than multiplying by 10^x first?

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Not really. Multiplying it out isn't really that difficult.

    You can add .5 and cast to int rather than using the C99 round function:
    Code:
    double nearest_percent(double n) {
        return (int)(n * 100 + .5) / 100.0;
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    Got it, thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Format Precision & Scale
    By mattnewtoc in forum C Programming
    Replies: 1
    Last Post: 09-16-2008, 10:34 AM
  2. Replies: 1
    Last Post: 04-03-2008, 01:17 AM
  3. IEEE Representation of Floats
    By Pnevma in forum C Programming
    Replies: 4
    Last Post: 01-28-2008, 10:06 AM
  4. Precision based floating-point
    By Mario F. in forum C++ Programming
    Replies: 4
    Last Post: 07-17-2006, 10:35 AM
  5. % and floats
    By confuted in forum C++ Programming
    Replies: 2
    Last Post: 08-04-2003, 09:41 PM