I have been working on a vb.net project and have run into a problem. I have tried various implementations from Stackoverflow and MSDN but nothing is working. All I am trying to do is convert a string value to a single and keep the precision.
An example of the code would be something like this:
Dim Total As Single = 0
Dim s as String = "427.00"
Total += Single.Parse(s)
// Total = 427
// Expected : 427.00 <-- I need this
I have tried using cultureinfo.invariant,
I have tried using string.format,
I have tried using double instead of single,
I don't know what I am missing.
Any insight would be appreciated, and I can provide more code of what the application is trying to do if necessary.
In addition to #Alex B.'s comment, this is how you would achieve this. Total is a String but the program will bomb if either is not a Single type giving you some type safety.
Dim Total As String = "0"
Dim s as String = "427.00"
Total = (Single.Parse(Total) + Single.Parse(s)).ToString("0.00")
Related
I am not a professional programmer, just FYI.
I am having trouble splitting a string. The resulting array has a length of 3, with the second spot (index 1) being completely empty.
I could manipulate the array to work the way I'd like, but I would rather understand why it is acting this way and code it properly from the beginning.
Dim defaultSetting() As String
Dim curSetting as String = "MENU_ITEM_ON_OPEN;;OPTIONAL_LEAVE"
defaultSetting = curSetting.Split(";;")
MsgBox(defaultSetting.Length) 'this is 3
MsgBox(defaultSetting(0)) 'this is as expected "MENU_ITEM_ON_OPEN"
MsgBox(defaultSetting(1)) 'this is empty and I do not know why
MsgBox(defaultSetting(2)) 'this is "OPTIONAL_LEAVE" and should be stored in defaultSetting(1)
Any help would be appreciated, thank you.
The problem here is that Option Strict is set to Off.
The overload of Split which is used expects a ParamArray of Char.
Because of this, the string ";;" is "silently" converted to a single char.
You can check this with following code:
Dim x As Char = ";;"
MsgBox(x)
You want to split by a string, which means you have to use another overload:
defaultSetting = curSetting.Split({";;"}, StringSplitOptions.None)
Thanks to a comment made by dbasnett I was able to find code that worked the way I was expecting, although I am not really sure why if anyone care to explain. But if not, this question has been answered, thanks.
defaultSetting = testString.Split(CType(";;", Char()), StringSplitOptions.RemoveEmptyEntries)
I have a string that says:
calculation = "10+3-2"
print(calculation) # This should equal 11
I can't figure out a way the string so Python would do the math. I have tried splitting the string etc but nothing worked.
Can someone please help? Thanks.
Try using the eval() function:
calculation = eval("10+3-2")
print(calculation)
or
calculation = "10+3-2"
print(eval(calculation))
I have a pretty technical question for which I don't imagine the answer and I would like to get an advice for optimization issues.
In my sheet, I've built a lot of XML lines. Specifically, they are 389,256 lines spread across the Range("A1") -> Range("A389256").
My objective is to build a string which contains all these lines, to hence fill it into an XML file. I do this with the following piece of code:
Private Function buildFileText() As String
Dim ss As String
Dim j As Long
For j = 1 To Sheets("FileContent").Range("A1").End(xlDown).Row
ss = ss & Sheets("FileContent").Range("A" & j).Value & vbNewLine
Next j
buildFileText = ss
End Function
Basically, I just build the string starting from an empty string and adding line by line all the content of my spreadsheet.
What is scaring is the time that this piece of code takes to execute: I've put a timer right before and right after the For loop, and it took 1 hour and 44 minutes to execute.
I don't find this behavior normal, because although the high number of lines, if I try to perform the same action on (let's say) 10,000 lines, it takes not even a second. Imagining it would take a second, I would expect the whole action to take 1 second*40=40 seconds approximately.
On the other hand, if it was a purely memory issue, I would have expected a stack overflow which didn't occur. So it seems the time it takes to perform each concatenation grows exponentially.
My questions:
Would anyone explain me why this is happening?
Does anyone have any suggestion to improve the performance of this code? Maybe I should split the concatenation in several strings (say 40 strings of 10k lines each) and concatenate each of them at a later stage?
It does not take a long time to initialize Huge strings.
Strings are not resizable. When you concatenate two strings together a Temp string is created to can hold both values. The values are then assigned to the Temp string and the target string is then replaced with the temp string.
Why does it take less than a Second for the first 10,00 lines and 389,256 takes 1 hour and 44 minutes?
"So it seems the time it takes to perform each concatenation grows exponentially" - It is actually growing at a consistent rate. If it were growing exponentially Excel would crash pretty quickly.
But the problem is that it is growing and every time you concatenate more memory is needed to create the new larger strings.
What can we do to improve performance?
In your case I would use MSXML2 to create the XML output. It is well documented will make your code easily extendable.
The second option is to implement a String Builder Pattern. String Builders reduce the number of concatenations by initializing a very large output string and writing the new strings to the next position in the output string.
My answer to Excel vba xml parsing performance shows how use a String BUilder Pattern to expost an Excel table as XML. Parfiat's answer to the same question demonstrates how to use MSXML2 to create the XML file.
other than the ways you see in comments, you may also want to try an "array" approach
whose maximum array size limitation can be overcome by splitting it in as much subarrays as necessary, as follows:
Private Function buildFileText() As String
Dim ss As String
Dim count As Long
With Worksheets("FileContent")
With .Range("A1", .Cells(.Rows.count, 1).End(xlUp))
Do While .count - count > 24684
ss = ss & Join(Application.Transpose(.Offset(count).Resize(24684).Value), vbNewLine)
count = count + 24684
Loop
buildFileText = ss & Join(Application.Transpose(.Offset(count).Resize(.count - count).Value), vbNewLine)
End With
End With
End Function
In a Visual Basic 6.0 program, I have a string sTemp that I want to ensure does not contain a quotation mark. I have the line:
If sTemp.Contains("""") Then
But when I type the period after sTemp, I don't get anything from intellisense, and when I try to compile I get the following error:
Compile error:
Invalid qualifier
VB6 strings are not objects, so there are no methods on the string variable that you can call.
To test does the string contain quotes you need to use the InStr function i.e.
if InStr(sTemp, """") > 0 then ' string contains at least one double quote
Hope this helps
UPDATE This has nothing to do with the original question
William, I just thought of this, it is unrelated information that you may find useful.
There are many ways to shoot yourself in the foot with VB6.
Among the less obvious is the fact that
Dim myCollection as new Collection
will have side effects you could never imagine.
Never DIM something AS New CSomething
Dim your variable, then on a second line, assign it to a new object. Hope this helps.
Dim myCollection as Collection
Set myCollection = New Collection
Try if instr(sTemp, """") > 0 then
Well, thats it!
I need to convert a string text (like"Hrd$457"), into a long value.
The blackberry IDE has a button that do it, but i need do this by code.
Please note that the string is alpha numeric.
THX!
NOTE:
Sorry if my question was not really clear. The IDE button that im talkin about converts the entire string in a long value that makes that string a unique number. The BlackBerry documentation says:
"To create a unique long key, in the BlackBerry® Integrated Development Environment, type a string value.
com.rim.samples.docs.userinfo
Right-click the string and click Convert ‘com.rim.samples.docs.userinfo’ to long."
So, i need to do exactly the same but by code.
I really appreciate your help buddies, and thanks so much for trying to help.
If you are just looking for a number constant for a string you can do the following.
String str = "asdfasdf345asdfasdf";
int asInt = str.hashCode();
long asLong = (long) asInt;
Returns the first 8 bytes of a SHA1 digest as a long. The same result can be obtained interactively using the BlackBerry JDE by highlighting a string, right-clicking, and choosing "Convert '' to long" from the context menu.
long net.rim.device.api.util.StringUtilities.stringHashToLong(String key)
This is another approach. If there are multiple numbers you can loop through the String using the scanner.
Scanner scanner = new Scanner(str);
scanner.useDelimiter("\\D+");
Long number = scanner.nextLong();
Not sure I fully grasp your example, but how's this?
String match = Pattern.compile("\\d+").matcher("Hrd$457").group();
long longValue = Long.parseLong(match).longValue();