How can I omit the first character for value in vb.net? - vb.net

I have this var:
Dim number as decimal = -61.52
and I want to delete the first character to be like this:
61.52
I tried to do this. but doesn´t work:
number = Trim(Left(number , Len(number ) - 1))
How can I do this?

You're looking for Math.Abs(), which forces a number to not be negative.

If you really want to treat a number as a string and then do string manipulations on it, you want to use the ToString method on your number. This will let you specify how you want the number formatted.
Dim NumberAsString As String
NumberAsString = number.ToString()
NumberAsString = NumberAsString.SubString(1, NumberAsString.Length - 1)
Note: you shouldn't rely on the default implementation as it will use the current UI culture and not guaranteed to give consistent results if executed under different cultures than when you developed it.

Related

What expression to use to capture middle part of a string

Beginner here. 2nd day into VB.
How do I capture the middle part of the string below? What method (Split, Contains, Trim, eg) to use?
Variable string message1:
"background:url(//test.image.com/bao/uploaded/i2/1951211594/TB2m1gjzYlmpuFjSZFl>XXbdQXXa_!!1951211594.jpg_40x40q90.jpg)"
To become:
//test.image.com/bao/uploaded/i2/1951211594/TB2m1gjzYlmpuFjSZFlXXbdQXXa_!!19512>11594.jpg
Dim s
s = Split(strMessage, ":url(")(1)
s = Left(s, Len(s)-2)
If you know the string will always contain "background:url( in the beginning and )" at the end, you can just use Mid$(message1, 17, Len(message1) - 18).

CDec doesn't return the correct value

I make code that multiply all values of a DatagridView column. The code is working, but there's a problem. In particular, I've added this:
Return CDec(x.Cells("Quote").Value.ToString.Replace(",", "."))
That returns me the split value, for example, if I would have:
2,7 the correct value to return is: 2.7, but the code returns 27 and this is strange. I performed some trying, and if I delete the CDec like:
Return x.Cells("Quote").Value.ToString.Replace(",", ".")
The value returned is correct, but I've a contrast with this function:
Private Function MultiplyDecimals(ByVal sender As Decimal()) As Decimal
Dim Result As Decimal
If Not sender Is Nothing AndAlso Not sender.Length = 0 Then
Result = sender.Aggregate(Function(a, b) a * b)
End If
Return Result
End Function
That returns me 0 if I delete "As Decimal". So what's wrong?
UPDATE with possible solution:
Dim bles = x.Cells("Quote").Value.ToString.Replace(",", ".")
Dim key = Convert.ToDecimal(bles)
MessageBox.Show(key)
Return CDec(key)
Since it looks like you are also trying to manually convert from a different culture, you should use the .NET methods for this, rather than roll your own. You have two conversions going on: From one cultural number system to another and from string to a numeric type.
To convert a string like "2,7" which might be a French or Italian value:
Dim str As String = "2,7"
Dim decVal As Decimal
If Decimal.TryParse(str, NumberStyles.AllowDecimalPoint,
New CultureInfo("it-IT"), decVal) Then
' decVal has the value
Else
' Parse failed
End If
or:
Dim cult As New CultureInfo("fr-FR")
If Decimal.TryParse(str, NumberStyles.AllowDecimalPoint,
cult, decVal) Then ...
This can often work, but you might get an exception depending on the content:
Dim decVal As Decimal
Dim cult As New CultureInfo("fr-FR")
decVal = Convert.ToDecimal(str, cult)
Console.WriteLine(decVal.ToString)
Note: I am guessing at the culture of the data. Based on your recent, related question Google indicates "Nazione" is Italian, but data from/about Algeria might well be French Algerian.
CDec, like most of the legacy VB functions, is only equipped to work with the active culture settings. So, it will seem like it is "broken" in some cases:
Console.WriteLine(CDec("2.7")) ' --> 2.7D US/Can
Console.WriteLine(CDec("2,7")) ' --> 27D
Console.WriteLine(CDec("2,,7")) ' --> 27D
On a machine using French or Italian culture, the opposite will happen: "2.7" will come out 27, "2,7" to 2.7D, but "2,,7" will probably crash just like "2..7" would in the US/Can.
The reason for this behavior is that in US/Can, a comma looks like noise and CDec ignores it. A string with a single decimal-dot will convert, but a string with 2 is invalid. It would be the reverse for French where the comma is used: any number of dots look like noise, and only single decimal-comma format will parse.
It is all part of the reason no one included CDec in the solution: It is sub-optimal for any sort of cultural conversions. Manually removing or replacing decimal markers is even less optimal when there are methods designed to do that only when needed.
Since you have a string value, try Decimal.Parse() instead of CDec().
If that doesn't give you the result you expect, then either you're not handling the string that you think you are (in which case, try logging the exact string to a text file or similar so you can see exactly what you have), or the PC's culture settings are not what you think they are (it may be set to a culture that uses the comma, rather than a period, as the decimal separator), in which case try one of the Decimal.Parse() overloads that allows you to specify the culture, or perhaps even just remove the call to .Replace().

Java - Index a String (Substring)

I have this string:
201057&channelTitle=null_JS
I want to be able to cut out the '201057' and make it a new variable. But I don't always know how long the digits will be, so can I somehow use the '&' as a reference?\
myDigits substring(0, position of &)?
Thanks
Sure, you can split the string along the &.
String s = "201057&channelTitle=null_JS";
String[] parts = s.split("&");
String newVar = parts[0];
The expected result here is
parts[0] = "201057";
parts[1] = "channelTitle=null_JS";
In production code you chould check of course the length of the parts array, in case no "&" was present.
Several programming languages also support the useful inverse operation
String s2 = parts.join("&"); // should have same value like s
Alas this one is not part of the Java standard libs, but e.g. Apache Commons Lang features it.
Always read the API first. There is an indexOf method in String that will return you the first index of the character/String you gave it.
You can use myDigits.substring(0, myDigits.indexOf('&');
However, if you want to get all of the arguments in the query separately, then you should use mvw's answer.

CStr() vs. Str() vs. .ToString()

I want to know what exactly are the differences between CStr(), Str() and .ToString()?
Label1.Text = CStr(Int(Rnd() * 10))
and
Label1.Text = Str(Int(Rnd() * 10))
and
Label1.Text = Int(Rnd() * 10).ToString
If I use this condition:
If Label1.Text = "7" Then
'Some code here
End If
Str() doesn't work here. What's the difference?
ToString will call the .ToString() function on a particular instance.
In practice, this means that it will throw an exception if the object in
question is Nothing. However, you can implement .ToString() in your own
classes to get a useful string representation of your object, whereas
CType/CStr only work with built-in classes and interfaces.
CStr and CType(expression, String) are exactly equivalent (I'm not
sure where the other poster got the idea that CStr is faster). But they
aren't really functions, they're compiler directives that will emit very
different code depending on the declaration of expression. In most
cases, these directives call a bunch of internal VB code that tries to
get a reasonable string out of expression.
DirectCast(expression, String) assumes that the expression in
question really is a String and just casts it. It's the fastest of all
these options, but will throw an exception if expression is anything
other than a String.
As an Addition to the VBA/VB6 Environment where we have no ToString():
Str() is not aware of international representation. The decimal separator always is a dot (.).
As already mentioned above it prefixes the resulting string with a blank in case of positive values.
There also exists Str$(). The difference to Str() is the return type:
Str() returns a variant of type string, Str$() returns a string.
And Str$() is slightly faster then Str().
CStr() in contrast is aware of international representation. The decimal separator depends on the Windows international settings.
No additional prefixing for positive values will be done.
So if you need to convert a value type to a string and have to ensure a dot as a decimal separator and no prefixing blank, then use this syntax:
Dim d As Double
d = 123.456
Dim s As String
s = Trim(Str$(d))
I don't know about ToString() and i don't know about VB.NET
But in VB6 (Visual Basic 6):
Both of Cstr() and Str() converts values to string. but Cstr() is better because:
Str(): After converting to string it adds 1 space before positive numbers. for example: Str(22) > " 22"
Cstr(): After converting to string it never adds the above extra space - For best result use it with Trim() - Trim(Cstr(Variable))
Although not a problem in the code in the question, it is important to mention that Str() only converts numerical expressions to string, gives an error in other cases, so don't use it for converting values of a cell.
My answer is str() is evil as it always prepends a space for the sign character so if you are comparing values it fails. Instead use CStr() instead which does not do this.
You may comes across business logic that tries to do this:
Eg:
Dim sVar as String = "1"
Dim i as Integer = 1
console.write( cstr(i) = sVar )
Which outputs:
False
I lost a couple hours on this one as the code was quite deep in old code and was very difficult to grok in production environment where logging based debugging was all that was available.

Check for only digits in VB.NET String

I want to run a check on a String right before I append it to a StringBuilder to make sure only numeric characters are in the string. What's a simple way to do that?
Use Integer.TryParse() it will return true if there are only digits in the string. Int32 max value is 2,147,483,647 so if your value is less then that then your fine.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
You can also use Double.TryParse() which has a max value of 1.7976931348623157E+308 but it will allow a decimal point.
If your looking to get the value that isnt an integer you can always go through the string one at a time
string test = "1112003212g1232";
int result;
bool append=true;
for (int i = 0; i < test.Length-1; i++)
{
if(!Int32.TryParse(test.Substring(i,i+1),out result))
{
//Not an integer
append = false;
}
}
If append stays true then the string is an integer. Probably a more slick way of doing this but this should work.
Coding in VB.Net to check whether a string contains only numeric values or not.
If IsNumeric("your_text") Then
MessageBox.Show("yes")
Else
MessageBox.Show("no")
End If
Use regular expressions:
Dim reg as New RegEx("^\d$")
If reg.IsMatch(myStringToTest) Then
' Numeric
Else
' Not
End If
UPDATE:
You could also use linq to accomplish the same task if you're doing it in VB.Net 2008/2010.
Dim isNumeric as Boolean = False
Dim stringQuery = From c In myStringToTest
Where Char.IsDigit(c)
Select c
If stringQuery.Count <> myStringToTest.Length Then isNumeric = False
If you do not wish to use RegEx, a simple check on each character with char.IsNumber works.
You can combine it with the All extension method (in C#, I don't know how to write it in VB.net):
string value = "78645655";
bool isValid = value.All(char.IsNumber);
Check out other char method, like IsDigit.
2 other compact solutions :
Without LINQ :
Dim foo As String = "10004"
Array.Exists(foo.ToCharArray, Function(c As Char) Not Char.IsNumber(c))
With LINQ (just VB.Net equivalent of the C# version in another answer) :
foo.All(Function(c As Char) Char.IsNumber(c))
Negative values haven't been mentioned, which Integer.TryParse would accept.
I prefer UInteger.TryParse which will reject a negative number. However, there is an additional check required in case the value starts with "+":
Dim test As String = "1444"
Dim outTest As UInteger
If Not test.StartsWith("+") AndAlso UInteger.TryParse(test, outTest) Then
MessageBox.Show("It's just digits!")
End If
or ULong.TryParse for a larger number.
Pattern matching! See this, this (about.com) and this (VB.NET dev article).
You can use regular expression or Integer.TryParse and I prefer the regular expression check
Presuming you're looking at relatively short strings which will never have a number greater than the Max Int32 value, use Gage's solution. If it's a variable length and sometimes you could overflow, use Regex (System.Text.RegularExpressions)
The regex for checking against just numbers is fairly routine: ^[0-9]+$
Check here for a very good explanation of Regex.