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#
  4. Floating point conversion with error

Floating point conversion with error

Scheduled Pinned Locked Moved C#
csharpquestiondatabasesql-servervisual-studio
7 Posts 4 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.
  • I Offline
    I Offline
    Ismael Oliveira 2021
    wrote on last edited by
    #1

    Hi.
    I use C# in Visual Studio and SQL Server. In my form I have a label that receives the name of a bank and a Textbox that must be filed with the bank balance. This couple repeats for the number of bank accounts of the client. After I retrieve the balances, I use the following snipet:
    if (TabSaldo.Rows.Count > 0)
    {
    for (i = 0; i < Nbancos; i++)
    {
    foreach (Control c1 in Gb_Bancos.Controls)
    {
    if (c1.Name.Contains("Lb_Banco" + (i + 1).ToString()))
    c1.Text = LinhaSaldo[i].ItemArray[1].ToString();

                        if (c1.Name.Contains("Tb\_Banco" + (i + 1).ToString()))
                        {
                            c1.Text = LinhaSaldo\[i\].ItemArray\[2\].ToString();
                            TotalBancos += float.Parse(LinhaSaldo\[i\].ItemArray\[2\].ToString()) / 100;
                        }
                    }
                }
            }
    

    It's working fine, but when I make the conversion from string to float (line starting with (TotalBancos +=) the conversion ignores the decimal point. Example: if the balance is 113,54 it sums 11354. As you see, I had to include a division by 100, for it to work. Please does anyone know what is wrong here?
    Thanks.

    OriginalGriffO L J 3 Replies Last reply
    0
    • I Ismael Oliveira 2021

      Hi.
      I use C# in Visual Studio and SQL Server. In my form I have a label that receives the name of a bank and a Textbox that must be filed with the bank balance. This couple repeats for the number of bank accounts of the client. After I retrieve the balances, I use the following snipet:
      if (TabSaldo.Rows.Count > 0)
      {
      for (i = 0; i < Nbancos; i++)
      {
      foreach (Control c1 in Gb_Bancos.Controls)
      {
      if (c1.Name.Contains("Lb_Banco" + (i + 1).ToString()))
      c1.Text = LinhaSaldo[i].ItemArray[1].ToString();

                          if (c1.Name.Contains("Tb\_Banco" + (i + 1).ToString()))
                          {
                              c1.Text = LinhaSaldo\[i\].ItemArray\[2\].ToString();
                              TotalBancos += float.Parse(LinhaSaldo\[i\].ItemArray\[2\].ToString()) / 100;
                          }
                      }
                  }
              }
      

      It's working fine, but when I make the conversion from string to float (line starting with (TotalBancos +=) the conversion ignores the decimal point. Example: if the balance is 113,54 it sums 11354. As you see, I had to include a division by 100, for it to work. Please does anyone know what is wrong here?
      Thanks.

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      Why are you converting something to a string in order to parse it to a float? Either it's a string to start with - in which case it's a waste of time and looks like the coder didn't know what he was doing - or it is a numeric value already - in which case why are you trying to parse it at all? If I try to abstract your code:

              float tb = 0.0F;
              tb += float.Parse("666.66") / 100;
              Console.WriteLine(tb);
      

      Then I get what I expected: 6.6666 so there are a couple of possibilities: 1) LinhaSaldo[i].ItemArray[2] is not the value you expect it to be. 2) TotalBancos is not a floating point variable. We can't check either of those so, it's going to be up to you. Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need. Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why. Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      I 1 Reply Last reply
      0
      • I Ismael Oliveira 2021

        Hi.
        I use C# in Visual Studio and SQL Server. In my form I have a label that receives the name of a bank and a Textbox that must be filed with the bank balance. This couple repeats for the number of bank accounts of the client. After I retrieve the balances, I use the following snipet:
        if (TabSaldo.Rows.Count > 0)
        {
        for (i = 0; i < Nbancos; i++)
        {
        foreach (Control c1 in Gb_Bancos.Controls)
        {
        if (c1.Name.Contains("Lb_Banco" + (i + 1).ToString()))
        c1.Text = LinhaSaldo[i].ItemArray[1].ToString();

                            if (c1.Name.Contains("Tb\_Banco" + (i + 1).ToString()))
                            {
                                c1.Text = LinhaSaldo\[i\].ItemArray\[2\].ToString();
                                TotalBancos += float.Parse(LinhaSaldo\[i\].ItemArray\[2\].ToString()) / 100;
                            }
                        }
                    }
                }
        

        It's working fine, but when I make the conversion from string to float (line starting with (TotalBancos +=) the conversion ignores the decimal point. Example: if the balance is 113,54 it sums 11354. As you see, I had to include a division by 100, for it to work. Please does anyone know what is wrong here?
        Thanks.

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

        You should not use float or double types in financial applications, as they can lose precision. Use the Decimal type or convert all values to the smallest denomination (cents etc.) and use integers..

        I 1 Reply Last reply
        0
        • I Ismael Oliveira 2021

          Hi.
          I use C# in Visual Studio and SQL Server. In my form I have a label that receives the name of a bank and a Textbox that must be filed with the bank balance. This couple repeats for the number of bank accounts of the client. After I retrieve the balances, I use the following snipet:
          if (TabSaldo.Rows.Count > 0)
          {
          for (i = 0; i < Nbancos; i++)
          {
          foreach (Control c1 in Gb_Bancos.Controls)
          {
          if (c1.Name.Contains("Lb_Banco" + (i + 1).ToString()))
          c1.Text = LinhaSaldo[i].ItemArray[1].ToString();

                              if (c1.Name.Contains("Tb\_Banco" + (i + 1).ToString()))
                              {
                                  c1.Text = LinhaSaldo\[i\].ItemArray\[2\].ToString();
                                  TotalBancos += float.Parse(LinhaSaldo\[i\].ItemArray\[2\].ToString()) / 100;
                              }
                          }
                      }
                  }
          

          It's working fine, but when I make the conversion from string to float (line starting with (TotalBancos +=) the conversion ignores the decimal point. Example: if the balance is 113,54 it sums 11354. As you see, I had to include a division by 100, for it to work. Please does anyone know what is wrong here?
          Thanks.

          J Offline
          J Offline
          jsc42
          wrote on last edited by
          #4

          Could, in addition to the ideas from the other respondents, be a culture thing. In some cultures, ',' is a thousands separator so your 113,54 could be treated as a misplaced thousands separator and assumed to be 11,354 which is 11354. If in your culture ',' is a decimal separator (which I am guessing is why you are dividing by 100 to get 113.54 [using my locale's decimal separator]) and your program is not using the same culture then it will misinterpret the value. See, for example, c# - float.Parse() doesn't work the way I wanted - Stack Overflow[^] See, for example, Single.Parse Method (System) | Microsoft Docs[^] (I know this is for single, rather than for float; but they work the same way and the version for float is playing hide-and-seek).

          I 1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            Why are you converting something to a string in order to parse it to a float? Either it's a string to start with - in which case it's a waste of time and looks like the coder didn't know what he was doing - or it is a numeric value already - in which case why are you trying to parse it at all? If I try to abstract your code:

                    float tb = 0.0F;
                    tb += float.Parse("666.66") / 100;
                    Console.WriteLine(tb);
            

            Then I get what I expected: 6.6666 so there are a couple of possibilities: 1) LinhaSaldo[i].ItemArray[2] is not the value you expect it to be. 2) TotalBancos is not a floating point variable. We can't check either of those so, it's going to be up to you. Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need. Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why. Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!

            I Offline
            I Offline
            Ismael Oliveira 2021
            wrote on last edited by
            #5

            Hi, OriginalGriff. I use debugging and the values retrieved are correct. The line

            LinhaSaldo[i].ItemArray[2]

            is used because of the code:

                        DataTable TabSaldo = Banco.LeSaldoBanco(Dtp\_DataSaldo.Text);
                        DataRow\[\] LinhaSaldo = TabSaldo.Select(null, null, DataViewRowState.CurrentRows);
            

            In this code I retrive data from the database and LinhaSaldo is used to access the data. The only form to do this that I know is by doing:

            c1.Text = LinhaSaldo[i].ItemArray[2].ToString();

            I've put messages to show me the retrieved values and they are OK, but after the line above, they are multiplied by 100. In other words, the decimal point was ignored. I´v tried many things, but none works. I also executed the program step by step, but nothing. If you have any suggestion, I would apprecciate it.

            1 Reply Last reply
            0
            • J jsc42

              Could, in addition to the ideas from the other respondents, be a culture thing. In some cultures, ',' is a thousands separator so your 113,54 could be treated as a misplaced thousands separator and assumed to be 11,354 which is 11354. If in your culture ',' is a decimal separator (which I am guessing is why you are dividing by 100 to get 113.54 [using my locale's decimal separator]) and your program is not using the same culture then it will misinterpret the value. See, for example, c# - float.Parse() doesn't work the way I wanted - Stack Overflow[^] See, for example, Single.Parse Method (System) | Microsoft Docs[^] (I know this is for single, rather than for float; but they work the same way and the version for float is playing hide-and-seek).

              I Offline
              I Offline
              Ismael Oliveira 2021
              wrote on last edited by
              #6

              Hi, jsc42. I tried what you suggested and it aparently works. Thanks.

              1 Reply Last reply
              0
              • L Lost User

                You should not use float or double types in financial applications, as they can lose precision. Use the Decimal type or convert all values to the smallest denomination (cents etc.) and use integers..

                I Offline
                I Offline
                Ismael Oliveira 2021
                wrote on last edited by
                #7

                Richard. I changed the types. Thanks for your help.

                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