Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Compare/Convert Float to Text

Compare/Convert Float to Text

Scheduled Pinned Locked Moved C / C++ / MFC
tutorial
30 Posts 14 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Maximilien

    bad answer, bad solution. You are rounding off values and killing performance. Read this : What Every Computer Scientist Should Know About Floating-Point Arithmetic[^] Max.

    Watched code never compiles.

    M Offline
    M Offline
    mohit 12
    wrote on last edited by
    #11

    How am i killing performance, well all i wanted to check is if the other float value is close or 0.10 and that code does check that i cannot use greater or less than since both float can be changed might be >0 or <0 , so rounding off values check if it's close to 0.10 or not because i do not have problem in my math if value if 0.0999978 or 0.10 both will give me same answer since it just checks value and then do not use them for any calculation, i will paste my code later on here and then you can have a look at it and you might be able to give me better suggestion, thx for reply tho cheers from canada.

    E 1 Reply Last reply
    0
    • I Iain Clarke Warrior Programmer

      You're kinda doing it wrong - at least in general. You code may work fine for your requirements! Try:

      BOOL IsEqualish (double d1, double d2, double dEpsilon)
      {
      ASSERT(dEpsilon > 0.0);
      d1 -= d2;
      if (d1 < 0.0)
      d1 = -d1; // or just d1 = abs (d1);
      return (d1 <= dEpsilon)
      }

      or for consise:

      BOOL IsEqualish (double d1, double d2, double dEpsilon) { return abs (d1 - d2) <= dEpsilon; }

      Where dEpsilon is the error margin. For 4 dps, dEpsilon = 0.0001, and so on. Iain.

      I am one of "those foreigners coming over here and stealing our jobs". Yay me!

      M Offline
      M Offline
      mohit 12
      wrote on last edited by
      #12

      I didn't get your code why would i use epsilon ? and it has to be FLOAT thx for reply. cheers from canada

      I 1 Reply Last reply
      0
      • A Aescleal

        I'm not a great one for going mental about code's performance but that's just horrible on so many levels. Why not do something like:

        bool near_enough_equals( double a, double b )
        {
        return (b - a) < ( (b + a) / 2000.0 );
        }

        Cheers, Ash

        M Offline
        M Offline
        mohit 12
        wrote on last edited by
        #13

        I am dealing with float and there is not way i can use DOUBLE for that particular code and my value might be negative so it might return negative value using your code and also b will be always less than a so negative :doh: thx for reply cheers from canada

        A 1 Reply Last reply
        0
        • N Niklas L

          Why use strings? Just round the values.

          double a = 1.00003;
          double b = 0.99997;
          a *= 100;
          b *= 100;
          a += 0.5;
          b += 0.5;

          if (::floor(a) == ::floor(b))
          {
          // Wooha!
          }

          home

          M Offline
          M Offline
          mohit 12
          wrote on last edited by
          #14

          floor will convert 0.099999787 to 0.10 ? and it has to be float value will it work ? thx cheers from canada.

          N 1 Reply Last reply
          0
          • L Luc Pattyn

            using strings for numeric information when you don't need strings is never the right approach. For numerical problems, use a numeric solution. Here are some possibilities: 1. you might put an upper limit on the deviation, similar to:

            float is=0.999999877543;
            float closeTo=1.0;
            bool closeEnough=abs(is-closeTo)<0.01;
            

            that would be close enough within 1% (since closeTo itself is one). 2. you might opt for a relative deviation (assuming the ideal value isn't zero):

            float is=12.999999877543;
            float closeTo=13.0;
            bool closeEnough=abs((is-closeTo)/closeTo)<1.0e-6;
            

            that would be close enough when within 1 ppm (pars pro million) :)

            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

            Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

            M Offline
            M Offline
            mohit 12
            wrote on last edited by
            #15

            as i mentioned in previous post those value can be changed so and it may vary from negative to zero and zero to +2.707 E06 so not sure if that would work.

            L 1 Reply Last reply
            0
            • M mohit 12

              as i mentioned in previous post those value can be changed so and it may vary from negative to zero and zero to +2.707 E06 so not sure if that would work.

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #16

              of course it can work. Whatever you can achieve with strings can be done without strings. FYI: electronic circuit simulators use a combination of absolute and relative tolerance, so they would do a convergence test similar to the following:

              float previous=...;
              float current=...;
              float threshold=0.1e-3; // an absolute tolerance of 0.1 millivolt for small voltages
              if (abs(previous)>1) threshold+=abs(previous)*100.0e-6; // a relative tolerance of 100 ppm
              bool converged = abs(current-previous) < threshold;

              in reality the two magic constants are variables, as the user is allowed to choose their value. :)

              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

              Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

              1 Reply Last reply
              0
              • M mohit 12

                thx all for your support.. nvm it i solved it ..stupid ME ... just added this method: bool classname::isStringEquals(float fNewNumber,float fOldNumber) { CString value1; CString value2; value1.Format( _T("%.4f"), fNewNumber); value2.Format( _T("%.4f"), fOldNumber); if(value1==value2) return true; else return false; cheers from canada

                T Offline
                T Offline
                Tim Craig
                wrote on last edited by
                #17

                mohit`12 wrote:

                if(value1==value2) return true; else return false;

                Ok, setting aside your real problem, why not simply code this as: return (value1 == value2); Call me anal if you like, but that's so much simpler and easier to read.

                Once you agree to clans, tribes, governments...you've opted for socialism. The rest is just details.

                1 Reply Last reply
                0
                • M mohit 12

                  I didn't get your code why would i use epsilon ? and it has to be FLOAT thx for reply. cheers from canada

                  I Offline
                  I Offline
                  Iain Clarke Warrior Programmer
                  wrote on last edited by
                  #18

                  mohit`12 wrote:

                  I didn't get your code why would i use epsilon ?

                  You yourself brought up the problem of floating point numbers being not perfect - if you read some of the links given you, you will realise that testing for equality is basically a waste of time. Digital computers simply do not do perfect representations of non-integers. Unless you're very lucky, and it's 1/(2^n). Two numbers can be reeeeeeeally close, and not equal. The simple fact you asked your original question shows that you know this already.

                  mohit`12 wrote:

                  and it has to be FLOAT

                  So change double to float. Or whatever FLOATs your boat. Not the hardest of challenges! Iain. ps, My code will also cope (as it should) with negative floating values.

                  I am one of "those foreigners coming over here and stealing our jobs". Yay me!

                  1 Reply Last reply
                  0
                  • M mohit 12

                    floor will convert 0.099999787 to 0.10 ? and it has to be float value will it work ? thx cheers from canada.

                    N Offline
                    N Offline
                    Niklas L
                    wrote on last edited by
                    #19

                    a = 0.09999;
                    a *= 100; // a = 9.999
                    a += 0.5; // a = 10.499
                    floor(a); // a = 10.0

                    b = 0.10001;
                    b *= 100; // b = 10.001
                    b += 0.5; // b = 10.051
                    floor(b); // b = 10.0

                    home

                    L 1 Reply Last reply
                    0
                    • M mohit 12

                      I am dealing with float and there is not way i can use DOUBLE for that particular code and my value might be negative so it might return negative value using your code and also b will be always less than a so negative :doh: thx for reply cheers from canada

                      A Offline
                      A Offline
                      Aescleal
                      wrote on last edited by
                      #20

                      Floats are converted to doubles before any serious arithmetic is done on them. The only reason you'd use a float is if you really had to save the 4 bytes (on most implementations). You actually introduce more arithmetic errors by saving everything as a float between calculations than doing everything as a double. As for the negative problem, use std::fabs or something on the values before processing them:

                      bool are_these_two_near_enough( double a, double b )
                      {
                      a = std::fabs( a ); b = fabs( b );

                      return std::fabs( a - b ) < ( ( a + b ) / 2000.0 );
                      

                      }

                      and if you're really worried about the difference between float and double use this as the function signature:

                      template< typename T >
                      bool are_these_two_floating_point_values_near_enough( T a, T b )

                      Edited as I didn't have all the HTML escapes properly sorted

                      modified on Tuesday, August 24, 2010 5:54 AM

                      1 Reply Last reply
                      0
                      • N Niklas L

                        a = 0.09999;
                        a *= 100; // a = 9.999
                        a += 0.5; // a = 10.499
                        floor(a); // a = 10.0

                        b = 0.10001;
                        b *= 100; // b = 10.001
                        b += 0.5; // b = 10.051
                        floor(b); // b = 10.0

                        home

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #21

                        ... and use "ceil" to round up value for example,

                        printf("ceil of 2.3 is %.1lf\n", ceil (2.3));

                        output

                        ceil of 2.3 is 3.0

                        to use the floor/ceil should be included math.h Sorry for my poor english. Best Regards, Alexander S.

                        N 1 Reply Last reply
                        0
                        • L Lost User

                          ... and use "ceil" to round up value for example,

                          printf("ceil of 2.3 is %.1lf\n", ceil (2.3));

                          output

                          ceil of 2.3 is 3.0

                          to use the floor/ceil should be included math.h Sorry for my poor english. Best Regards, Alexander S.

                          N Offline
                          N Offline
                          Niklas L
                          wrote on last edited by
                          #22

                          ?

                          home

                          L 1 Reply Last reply
                          0
                          • N Niklas L

                            ?

                            home

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #23

                            float a = 1.555;
                            float b = floor(a); // b = 1
                            float c = ceil(a); // c = 2

                            a = 0.09999;
                            b = floor(a); // b = 0
                            c = ceil(a); // c = 1

                            modified on Tuesday, August 24, 2010 1:56 AM

                            N 1 Reply Last reply
                            0
                            • L Lost User

                              float a = 1.555;
                              float b = floor(a); // b = 1
                              float c = ceil(a); // c = 2

                              a = 0.09999;
                              b = floor(a); // b = 0
                              c = ceil(a); // c = 1

                              modified on Tuesday, August 24, 2010 1:56 AM

                              N Offline
                              N Offline
                              Niklas L
                              wrote on last edited by
                              #24

                              fasked wrote:

                              Why add 0.5?

                              To turn floor() into a round()

                              home

                              1 Reply Last reply
                              0
                              • I Iain Clarke Warrior Programmer

                                You're kinda doing it wrong - at least in general. You code may work fine for your requirements! Try:

                                BOOL IsEqualish (double d1, double d2, double dEpsilon)
                                {
                                ASSERT(dEpsilon > 0.0);
                                d1 -= d2;
                                if (d1 < 0.0)
                                d1 = -d1; // or just d1 = abs (d1);
                                return (d1 <= dEpsilon)
                                }

                                or for consise:

                                BOOL IsEqualish (double d1, double d2, double dEpsilon) { return abs (d1 - d2) <= dEpsilon; }

                                Where dEpsilon is the error margin. For 4 dps, dEpsilon = 0.0001, and so on. Iain.

                                I am one of "those foreigners coming over here and stealing our jobs". Yay me!

                                H Offline
                                H Offline
                                hairy_hats
                                wrote on last edited by
                                #25

                                I think you want

                                fabs

                                for C/C++.

                                I 1 Reply Last reply
                                0
                                • H hairy_hats

                                  I think you want

                                  fabs

                                  for C/C++.

                                  I Offline
                                  I Offline
                                  Iain Clarke Warrior Programmer
                                  wrote on last edited by
                                  #26

                                  viaducting wrote:

                                  I think you want fabs

                                  You'd be right, too! That's what happens when you code in a text editor... Not to worry - the OP is convinced all I typed was rubbish anyway! But good to point out an error, in case it helps someone else. Iain.

                                  I am one of "those foreigners coming over here and stealing our jobs". Yay me!

                                  1 Reply Last reply
                                  0
                                  • M mohit 12

                                    I am trying to convert float to text. the reason i am doing this is because the float contains 0.09999987 and i want that variable as 0.10 and then compare it to other float which is initially 0.10000 if anyone have idea how to convert float to text let me know thx, cheers from Canada.

                                    J Offline
                                    J Offline
                                    Jeff Archer
                                    wrote on last edited by
                                    #27

                                    Here is a very good article on comparing floats. This method is much better than converting to text for the comparison. http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm[^]

                                    L 1 Reply Last reply
                                    0
                                    • M mohit 12

                                      How am i killing performance, well all i wanted to check is if the other float value is close or 0.10 and that code does check that i cannot use greater or less than since both float can be changed might be >0 or <0 , so rounding off values check if it's close to 0.10 or not because i do not have problem in my math if value if 0.0999978 or 0.10 both will give me same answer since it just checks value and then do not use them for any calculation, i will paste my code later on here and then you can have a look at it and you might be able to give me better suggestion, thx for reply tho cheers from canada.

                                      E Offline
                                      E Offline
                                      englebart
                                      wrote on last edited by
                                      #28

                                      Performance is killed because CString will new and delete memory to hold the chars for both instances. If this is in a highly used piece of code, you could fragment the heck out of your heap. The Epsilon isEqualish(float, float, float) approach is the best. An alternative would be to use a Fixed Point numeric class that would exactly represent a decimal value, but that might also have performance implications. It all depends on what you are doing. Skip the CString.Format even though it seems convenient.

                                      1 Reply Last reply
                                      0
                                      • J Jeff Archer

                                        Here is a very good article on comparing floats. This method is much better than converting to text for the comparison. http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm[^]

                                        L Offline
                                        L Offline
                                        Luc Pattyn
                                        wrote on last edited by
                                        #29

                                        Nice link! :)

                                        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                                        Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

                                        1 Reply Last reply
                                        0
                                        • M mohit 12

                                          I am trying to convert float to text. the reason i am doing this is because the float contains 0.09999987 and i want that variable as 0.10 and then compare it to other float which is initially 0.10000 if anyone have idea how to convert float to text let me know thx, cheers from Canada.

                                          G Offline
                                          G Offline
                                          glwentworth
                                          wrote on last edited by
                                          #30

                                          don't convert it to text just decide what the acceptable error is and compare ...

                                          float error = 0.00000013;
                                          float lowv = 0.1 - error;
                                          float highv = 0.1 + error;

                                          if ((lowv <= myfloat) && (highv >= myfloat)) {
                                          // good value
                                          } else {
                                          // bad value
                                          }

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups