floating point error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandeepdhankar10
    New Member
    • Dec 2008
    • 36

    floating point error

    hi experts,

    i am facing trouble with float data types.

    when i try to parse a value to float it gives me diffrent value.

    e.g float test = (float.Parse("1 49.128156"));

    gives me test=149.128159

    i am very fed up of this.. pls help me out ...

    i want the exact values of what i gave as input.

    thanks in advance
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    More about floats than you would want to know:


    But I do notice that a double works fine for your example:
    Code:
                float Test = float.Parse("149.128156");// Breakpoint here and walk through looking at Locals values
                float Bob = Test;// Yep, Bob is wrong here
                MessageBox.Show("Parse",Test.ToString());
                double Yogi = double.Parse("149.128156");
                double booboo = Yogi;// But Yogi is right here
                MessageBox.Show("Double", Yogi.ToString());

    Comment

    • sandeepdhankar10
      New Member
      • Dec 2008
      • 36

      #3
      thanks tlhintoq fro your response.

      i know that i can get my values by using double..

      but i have a problem in which i must have to use float.

      so pls give me some suggestion by which i can get perfect values in float

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        Since you know parsing to a double gets you the right value, I would experiment from that. Parse to a double, then seat a float equal to the double; and so on. See if some combination of those get you a usable float as the final step.

        Comment

        • sandeepdhankar10
          New Member
          • Dec 2008
          • 36

          #5
          i do not get you .. can you pls little more specific with a small example/..

          thanks in advance

          Comment

          • tlhintoq
            Recognized Expert Specialist
            • Mar 2008
            • 3532

            #6
            Code:
            double Yogi = double.Parse("149.128156");
            float bob = Yogi
            // the Double does the parsing accurately
            // then gives it to a float for you to use elsewhere per your need to use a float.

            Comment

            • sandeepdhankar10
              New Member
              • Dec 2008
              • 36

              #7
              thanks for your response but...
              its not working b/c there is no implicit conversion from double to float .in c#
              we have to write as follows
              float bob =(float) Yogi;

              then it again gives me 149.128159

              so still i have same problem.

              Comment

              Working...