Results 1 to 13 of 13

Thread: decimals places in texboxes

  1. #1

    Thread Starter
    Member
    Join Date
    Feb 2018
    Location
    UK
    Posts
    49

    decimals places in texboxes

    Hi all,
    In my project I get data from a database into a DGV then I loop down a column of figures(student marks) to find an average.The average figure is then placed into a textbox.Here is an example code
    Code:
    Dim sum as double
    Dim d as single
    On Error Resume Next
      For q=0 to 5
        sum +=
       DataGridView1.Rows(g).Cells("marks").Value()
    On Error Resume Next
    Next
    It works fine but the problem is with the display of the number in the texboxes.I am trying to get it down to two decimal places,something like this:
    21.23
    or beter still this
    21.3
    however I am getting this
    21.3333333333 etc
    I have treid a few things like changing the format of the column in the database,but it doesn't work.I cant find anything in the TB properties either
    Any suggestions much appreciated
    cheers
    al

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,943

    Re: decimals places in texboxes

    Don't use a textbox for numbers. The NumericUpDown control accepts only numbers, allows you to set the number of decimal places, and returns a number from the .Value property. A textbox ONLY returns strings, which means you have to do other things to turn the text back into a number.

    On the other hand, the way you wrote that, it looks like you are using the textbox just for output, in which case you should use a label. Textboxes suggest to the user that something will happen if they change what the textbox holds, which isn't the case if it is just used for display. A label doesn't carry that suggestion.

    The DGV likely holds an Object, so you would turn it into a string with .ToString. ToString can take a format argument. To get a number into two decimal places, it would be .ToString("N2")

    Additionally, you should turn Option Strict ON for the project (Project | Properties on the Compile tab), or for ALL projects (somewhere in Tools | Options). All that does is prevents you from using implicit conversions, which are a bit slower than explicit conversions, but can also hide bugs that won't show up until the program crashes.

    Finally, On Error Resume Next is not just a holdover from VB6, it's a particularly horrible one. All that's doing is ignoring any errors. Errors are slow and they're....errors, so you want to fix them, not ignore them. Try....Catch is the .NET means of error handling. You still shouldn't ignore the errors, though.
    My usual boring signature: Nothing

  3. #3
    Fanatic Member kpmc's Avatar
    Join Date
    Sep 2017
    Posts
    1,012

    Re: decimals places in texboxes

    Code:
            Dim Textbox1 As New TextBox
            Dim MyDbl As Double = 2.333333333333333
            Textbox1.Text = Math.Round(MyDbl, 2).ToString

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,943

    Re: decimals places in texboxes

    Yeah, but .ToString("N2") is a whole lot easier to type.
    My usual boring signature: Nothing

  5. #5
    Fanatic Member kpmc's Avatar
    Join Date
    Sep 2017
    Posts
    1,012

    Re: decimals places in texboxes

    Quote Originally Posted by Shaggy Hiker View Post
    Yeah, but .ToString("N2") is a whole lot easier to type.
    I like the way you think

  6. #6
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: decimals places in texboxes

    Well, it's more reliable, too.

    The thing is, floating-point numbers only have so much precision. There are 64 bits available, and while that can represent a lot of numbers it is also true there are an infinite amount of numbers between 0 and 1. Since "infinite" can't be represented in 64 bits, obviously some compromise had to be made.

    Also, it seems lost on a lot of people that what .ToString() does is very important. It converts a type from a number to a string. This is interesting because Strings can represent a number many different ways. The way we control how it comes out is that format specifier parameter. So when we pass "N2", we're saying "Please convert the number to a string by rounding it and displaying up to two decimal places."

    How is that different than Math.Round?

    Suppose we have some value that can't be represented well in a Double, like 0.3333333.... So we try to fit it into two decimal places with Math.Round(). But maybe 0.33 can't be perfectly represented, either. So it's possible that:
    Code:
    Console.WriteLine(Math.Round(0.33333, 2).ToString())
    Might still print "0.33333333". Why? Well, Math.Round() will rightly try to change the number to 0.33. But if that number can't be represented properly in Double, you're going to get 0.33?????, where the ? is more or less random for this discussion. And the default .ToString() implementation will print any non-zero trailing decimal digits.

    But if you:
    Code:
    Console.WriteLine(0.333333.ToString("N2"))
    The number is converted to a String with rules that know to completely ignore the trailing characters.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  7. #7

    Thread Starter
    Member
    Join Date
    Feb 2018
    Location
    UK
    Posts
    49

    Re: decimals places in texboxes

    Hi all,
    This is a really interesting discussion with some illuminating replies.But can someone explain this to me.If I place 3 TextBoxes on a form and 1 button.then place the following code
    Code:
    TextBox1.Text
    TextBox2.Text 
    TextBox3.Text =TextBox1.Text+TextBox2.Text
    Now lets say I put 20 in TB1 and 20 in TB2 I get the result in a string format ie 2020 in TB3.
    However if I use */ or -(muliply,divide or minus) It actually gives me a numeric answer as opposed to just spilling out the string.So if I run the following code this will actually perform divisionlikewise for subtraction and multiplication
    Code:
    TextBox1.Text
    TextBox2.Text 
    TextBox3.Text =TextBox1.Text /TextBox2.Text
    Is there a reason for this.

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: decimals places in texboxes

    Quote Originally Posted by limelight View Post
    Hi all,
    This is a really interesting discussion with some illuminating replies.But can someone explain this to me.If I place 3 TextBoxes on a form and 1 button.then place the following code
    Code:
    TextBox1.Text
    TextBox2.Text 
    TextBox3.Text =TextBox1.Text+TextBox2.Text
    Now lets say I put 20 in TB1 and 20 in TB2 I get the result in a string format ie 2020 in TB3.
    However if I use */ or -(muliply,divide or minus) It actually gives me a numeric answer as opposed to just spilling out the string.So if I run the following code this will actually perform divisionlikewise for subtraction and multiplication
    Code:
    TextBox1.Text
    TextBox2.Text 
    TextBox3.Text =TextBox1.Text /TextBox2.Text
    Is there a reason for this.
    That's because you're not considering data types properly. The Text of a TextBox is type String. The '+' operator is defined for two Strings and so the first code adds the two Strings based on that, which means concatenating them. In the second code, there is no '/' operator defined for Strings so the system implicitly converts them to numbers; Double values to be precise.

    What you should be doing is ALWAYS using the appropriate data type for the operation being performed. If you want to add two numbers then use numbers, not text. The fact that a String contains digit characters does not make it a number. The first thing to do is to turn Option Strict On in the project properties AND the IDE options. That will force you to use appropriate data types. In this case, that code should be something like this:
    vb.net Code:
    1. TextBox3.Text = (CDbl(TextBox1.Text) + CDbl(TextBox2.Text)).ToString()
    You start by converting the String input to a numerical type, then you perform the arithmetic on those numbers, then you convert the result to a String for display. If you take Shaggy's advice and use a NumericUpDown rather than a TextBox then there's no conversion from text to number necessary, because the Value property is type Decimal. Also, the NumericUpDown control takes care of the validation, which you need to do yourself with a TextBox. The code I provided will fail if the user enters invalid text.

  9. #9
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: decimals places in texboxes

    The answer is kind of cruddy and part of the reason why VB is actually harder to learn than people give it credit for.

    Historically, VB wasn't very bothered by type conversions, and would do everything in its power to make a line work. So if you wrote a line that tried to multiply "20", a String, by 45.2, a number, it would happily convert the String to a number. So long as you memorized all the type conversion rules, you could "save time" by not typing a lot of casts. You made up for it by losing time in the debugger every time you made a mistake. "Oh, right, False can convert to a number, and then it gets converted to a String, that's why when I push the button I order Tide from Amazon instead of deleting a file."

    VB .NET introduced Option Strict, which was on by default for a while. This turns off most of the implicit conversion rules, so if you try to multiply a String by an Integer it will complain. The '+' operator is still sort of pesky in that case, most professionals agree to never, ever use it for String concatenation. Even more professionals agree using "&" for concatenation is a code smell, too. We prefer String.Format(), because it's not a loaded gun pointed at your foot.

    But VB6 developers hate VB .NET, and want to see Microsoft go out of business for creating it. So they screamed and yelled and harassed and threatened the VB .NET team. "We would love to update to VB .NET," they said, "but we can't port our code if Option Strict is on by default. Please change it and we'll upgrade to Windows 7 and VB .NET." So Microsoft listened, because Microsoft really, really wants VB6 programmers to join this quarter-century. Then the VB6 developers laughed and kept convincing people to use VB6 instead. This was the third or fourth time, and not the last. They could've just turned it off in their project, but VB6 developers would rather the world revolve around them.

    So Option Strict is off by default in VB .NET, and you have to tell Visual Studio to turn it on by default in both your project and VS settings. This leads to a post by a confused person at least once a week in these forums. C# newbies don't have this problem, because C#'s opinion is, "Sorry, I won't let you do math with a String and Integer, you're going to have to do some conversion." This helps you get past the newbie->novice transition faster, which means you can start using Option Infer to save time while still using the Option Strict safety net.
    Last edited by Sitten Spynne; Feb 10th, 2018 at 11:16 AM.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: decimals places in texboxes

    Quote Originally Posted by Sitten Spynne View Post
    VB .NET introduced Option Strict, which was on by default for a while.
    I don't think that that is true. I didn't use the original VB.NET (2002) but Option Strict was Off by default in 2003 and has been since. I was under the impression that it was Off by default in 2002 as well. Are you sure that it wasn't?

  11. #11

    Thread Starter
    Member
    Join Date
    Feb 2018
    Location
    UK
    Posts
    49

    Re: decimals places in texboxes

    Hi all,
    Thankyou for all of this detailed discussion,the + mystery solved plus an interesting history of how VB has developed.Absorbing stuff
    I would like to ask you all,is it better to learn C# rather than VB,or both
    Cheers
    al

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,943

    Re: decimals places in texboxes

    Both.

    It depends largely on what you want to do. Many people feel that MS is shifting more towards C# and away from VB. I'm inclined to say that they don't know what the future will hold, and will likely continue both languages for a long time. Moving from one .NET language to another is not too difficult. The syntax is different, but the structure of the languages is the same.

    Having said that, I would note that C# is in the C family of language syntaxes, along with C, C++, Java, JavaScript, and others. Therefore, if you know the C syntax, it will make a fair number of languages easier to move in to. Furthermore, there may be more jobs in C# than in VB, and even if there are not, it certainly appears that they tend to pay better, so, at least from a career perspective, C# is worth learning.
    My usual boring signature: Nothing

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: decimals places in texboxes

    I would agree that, without context, learning both is the best option. Even if you only ever intend to use VB, knowing C# will be beneficial when you come across examples that don't exist in VB. If you intend to do any web work then you'll almost certainly have to use JavaScript so, in that case, you can't avoid the C-based syntax anyway.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width