Modifying type precision

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tiddwaylll
    New Member
    • Jun 2008
    • 6

    Modifying type precision

    Hi,

    I need to "cast" a double precision to just two decimal places.
    For example, if I have a precision 1.114688, I want to turn this to 1.11.

    BUT not permanently, just for compare cases.

    The problem is actually comparing two numbers, and I only want an estimate. When I write
    if(a==b)
    then it always gives false, since with that high precision a will never be equal to b. But I am very sure they are equal at two decimal places. And again, I only want the change to be permanent, taking effect only during the if conditional.

    I know that I can
    printf("0.2%lf" , a);
    But that applies to the printf function and I don't know whether you can readily use it freely in other cases as well.

    Thank you!
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    When I write if(a==b) then it always gives false, since with that high precision a will never be equal to b.
    It’s more than that. Comparing floating points directly is a bad idea. There’s a number of good CS articles and the like out on the internet for you to read. The point is, the precision for floats and doubles is quite large, but the usage of a binary system makes comparison rather tricky.

    You have a few options in your comparison. Not sure which you will like best. If what you really want is to ensure that the numbers are quite close to each other, take the difference of the numbers, and ensure that the difference is less than 0.01 or some threshold.

    Sprintf will do the work of printf, but give you a string. You can compare two strings with strcpy.

    Also possible: multiply the numbers by 100, place them in an integer, and compare.

    Comment

    • tiddwaylll
      New Member
      • Jun 2008
      • 6

      #3
      Thanks for the reply.

      I should have thought of the subtraction earlier... But now I know better than to compare doubles precisions without thinking twice.

      Thanks!

      Comment

      • arnaudk
        Contributor
        • Sep 2007
        • 425

        #4
        Originally posted by oler1s
        You can compare two strings with strcpy.
        I think oler1s means strcmp. (strcpy copies strings).

        Comment

        Working...