is it possible to add 0 in double var in vb net?

Let’s look at this line piece by piece, and see what it actually does:

SecondsRemainder.ToString.PadLeft(2, "0")

We start with the SecondsRemainder variable. This variable is still a Double, in spite of the earlier code using Convert.ToInt32(). Remember, at it’s core VB.Net is a statically typed language! When you declare a variable with a specific type, the variable’s type can never change.

We now call the .ToString() method for this variable. Note this really is a method, not a property. Good practice for .Net is to include the parentheses when calling methods, even though they aren’t strictly required with VB. If I reviewed that code, I’d ask you to change it to show the parentheses. Remember, we’re also getting the Double version of this method, rather than the Integer version. You’re probably okay here, but the double version can do weird things for formatting you might not expect from an integer.

Finally, we take the string result from the previous method and call PadLeft(). This mostly does what you expect. However, there is no overload that takes a number and a string. Frankly, I’m surprised this even compiles, and it tells me you likely don’t have Option Strict set correctly. No self-respecting programmer runs with Option Strict Off anymore. The correct way to call this function is like this:

.PadLeft(2, "0"c)

Where the c suffix gives you a character value rather than a string value.

And that’s it. We’re done. This function returns a result. It does not modify the calling variable. So we’ve done all this work, and discard the result without actually changing anything.

What I would do to fix your issue is declare a new string variable to receive the result. Then I would use this code to assign to it:

'Create a string variable to hold your string result
Dim RemainderString As String = ""
'Use double literals to compare with double variables!
If SecondsRemainder >= 0.0 And SecondsRemainder < 10.0 Then 
    'Use a format string directly from the initial double value to create your string result
    ' and don't forget to assign it to a variable
    RemainerString = SecondsRemainder.ToString("00") 
End If

You may also want to use Math.Round() first, as this code would still create "01" from a 1.9999 input.

Finally, I’m wondering how you’re using this SecondsRemainder value. VB.Net has a whole set of methods for building date and time strings and values, and a variable name like SecondsRemainder sounds like you’re doing something the hard way that could be much MUCH easier.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top