restrict float(double) number

This is a discussion on restrict float(double) number within the C Programming forums, part of the General Programming Boards category; Hi when I input a float(double) number with scanf() or predefined like scanf("%f",&num);//input is 1.12 float num = 1.12; in ...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    173

    restrict float(double) number

    Hi

    when I input a float(double) number with scanf() or predefined like

    scanf("%f",&num);//input is 1.12
    float num = 1.12;

    in fact, num is not 1.12, it is something like 1.1200000000000000xxx or something,

    but how could I really restrict num to 1.12??

    I know there is something like FLT_EPSILON, but no idea how to use it, any idea??

    Thanks
    Don't laugh at me,I am just a SuperNewbie.

  2. #2
    SleepWalker tjohnsson's Avatar
    Join Date
    Apr 2004
    Posts
    70
    try print it out using: printf("%.2f\n", num); see what happens...
    and check printf, scanf etc... manual to see to get more information how to control formatted outputs / inputs.

    http://www.linuxselfhelp.com/gnu/gli...12.html#SEC207

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    173
    Thanks, but the problem is that we never know what kinds of number user will input, so we can't define "%.2f" before knowing the number.
    Don't laugh at me,I am just a SuperNewbie.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Use sprintf to stick the number into a buffer as a string, then work backwards from the end until you are no longer reading a zero. Add a null just past the last non-zero character, replacing the first trailing zero, and then just use %s (assuming you're using printf for output). Naturally you'll have to make an exception for the decimal point, in case you run into a number like "1.0".

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with this compiler error
    By Evangeline in forum C Programming
    Replies: 7
    Last Post: 04-05-2008, 09:27 AM
  2. Calculating next prime number
    By anilemon in forum C Programming
    Replies: 8
    Last Post: 04-17-2006, 10:38 AM
  3. Prime number program problem
    By Guti14 in forum C Programming
    Replies: 11
    Last Post: 08-06-2004, 04:25 AM
  4. parsing a number
    By juancardenas in forum C Programming
    Replies: 1
    Last Post: 02-19-2003, 12:10 PM
  5. Random Number problem in number guessing game...
    By -leech- in forum Windows Programming
    Replies: 8
    Last Post: 01-15-2002, 04:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21