Format number with default NumDigAfterDec and without rounding - vbscript

I am using in my sql server reports a simple vbscript command to format some numeric fields:
FormatNumber(value,,-1,0,-1)
Important for me is the second parameter NumDigAfterDec that is set to default, meaning
that "the computer's regional settings are used" (http://www.w3schools.com/vbscript/func_formatnumber.asp). This is exactly what I prefer. But when the current number has more digits after decimal, it is rounded. In this case I would like to see all places.
e.g. for two places after decimal, I would like:
0 0.00
90.7 90.70
1.2345 1.2345 (instead of 1.23)
Is this possible without writing code in my reports?

If I understand correctly, you want a condition stating if length of decimal is greater than 2 places, then display full decimal number, else 2 decimal places?
A simple way to do this is:
Dim value : value = "100.54367"
Dim GetDecCount : GetDecCount = Len(Mid(Value, instr(value, ".")+1, len(value)))
if GetDecCount>2 then
msgbox "This number exceeds the regional decimal points of 2, with a length of " & GetDecCount & " decimal points."
else
FormatNumber(value,,-1,0,-1)
end if

Try something like this:
Set re = New RegExp
re.Pattern = ".\d{3,}$"
if re.Test(value) Then
fnum = CStr(value)
Else
fnum = FormatNumber(value, , -1, 0, -1)
End If

Related

VB Control Naming by Variable

Dim LineNo as Integer
LineNo = CStr(channel) 'This can have a value of 1 to 100
If LineNo = 1 then
Text1.Text = "Line one selected"
Elseif LineNo = 2 then
Text2.Text = "Line one selected"
'Etc etc
End if
I need to replace the number "1" in Text1.Text and every other TextBox with the value of LineNo? For example:
Text{LineNo}.Text
So I would not have to do a repeated "If" and have a smaller one line code like this:
Text{LineNo}.Text = "Line " & LineNo & " selected"
How would I do this?
Look into a Control array of text boxes. You could have txtLine(), for example, indexed by the channel number.
LineNo = CStr(channel)
txtLine(channel).Text = "Line " & LineNo & " selected"
To create the array, set the Index property of each of the text boxes to an increasing integer, starting at 0.
If you have a finite and relatively small number, you can use a property. I've used this approach with up to 30+ elements in a pinch. Super simple, easy pattern to recognize and replicate in other places. A bit if a pain if the number of elements changes in the future, but extensible nevertheless.
It uses the Choose statement, which takes an index N and returns the Nth element (1-based), hence, the check makes sure that N is > 0 and <= MAX (which you would configure).
Public Property Get TextBox txt(ByVal N As Long)
Const MAX As Long = 10
If N <= 0 || N > MAX Then Exit Property ' Will return a "Nothing". You could return the bound element if you prefer
set txt = Choose(Text1, Text2, Text3, Text4, Text5, Text6, Text7, Text8, Text9, Text10)
End Property
Then, you can simply reference them with the Property, much like an alias:
txt(1).Text = "Line 1 text"
txt(2).Text = "Line 2 text"
If you have an arbitrary number, then you are likely using a control array already, which is simpler because it can be referenced by Index already, so you can directly reference it.
If neither of these work for you and you have a very large number of controls, you can scan the Controls collection in a similar Property, attempting to match ctrl.Name with the pattern of your choice (e.g., matching the first 4 characters to the string "Text", thus matching Text1, Text2, etc, for an unlimited number). Theoretically, this should be future-proofed, but that's just theoretical, because anything can happen. What it does do for you is to encapsulate the lookup in a way that "pretends" to be a control array. Same syntax, just you control the value.
Public Property Get TextBox txt(ByVal N As Long)
Dim I As Long
For I = 0 To Controls.Count - 1 ' Controls is zero-based
' Perform whatever check you need to. Obviously, if you have a "Label" named
' "Text38", the assignment will throw an error (`TextBox = Label` doesn't work).
If Left(Controls(I).Name, 4) = "Text" Then
set txt = Controls(I)
End If
Next
' If you want the Property to never return null, you could uncomment the following line (preventing dereference errors if you insist on the `.Text` for setting/getting the value):
' If txt Is Nothing Then Set txt = Text1
End Property
Use the same way as above: txt(n).Text = "..."

Random Characters added to String

I am trying to add a random set of numbers to the end of a string. I'm still learning the basics of VBS but this has really tricked me and I can't seem to find anything online.
I've tried:
string2 = "hello" + (Rnd() * Len(VALID_TEXT)) + 1
And:
x = rnd*10
string2 = "hello" + x
What am I doing wrong?
All random number generators rely on an underlying algorithm, usually fed by what’s called a seed number. You can use the Randomize statement to create a new seed number to ensure your random numbers don’t follow a predictable pattern.
To get the random numbers, using rnd alone is not sufficient as you will keep on getting the same random number again and again. You have to use randomize to achieve the task as shown below:
Dim strTest:strTest = "Hello"
Dim intNoOfDigitsToAppend:intNoOfDigitsToAppend = 5
Randomize
Msgbox "String before appending: " & strTest
strTest = fn_appendRandomNumbers(strTest,intNoOfDigitsToAppend)
Msgbox "String before appending: " & strTest
function fn_appendRandomNumbers(strToAppend,intNoOfRandomDigits)
Dim i
for i=1 to intNoOfRandomDigits
strToAppend= strToAppend & int(rnd*10) 'rnd gives a random number between 0 and 1, something like 0.8765341. Then, we multiply it by 10 so that the number comes in the range of 0 to 9. In this case, it becomes 8.765341. After that, we use the int method to truncate the decimal part so that we are only left with the Integer part. In this case, 765341 is truncated and we are left with only the integer 8
next
fn_appendRandomNumbers = strToAppend
end function
Reference 1
Reference 2
& is the string concatenation character. + is an old compatability concat character and will error if you mix text and numbers. Use + for maths only.

Usage of + operator in differents situations in vbscript

What is the Value of the below in vbscript
1)x=1+"1"
2)x="1"+"1"
3)x=1+"mulla"
Note:In the all above three cases I am using first variable as either string or integer and second on as always as string.
Case 1:Acting as a numeric and auto conversion to numeric during operation
enter code here
y=inputbox("Enter a numeric value","") Rem I am using 1 as input
x=1
msgbox x+y Rem value is 2
msgbox x*y Rem value is 1
Case 2:Acting as a String and no conversion to numeric during operation it fails
enter code here
y=inputbox("Enter a numeric value","") Rem I am using 1 as input
x=1
if y= x then
msgbox "pass"
else
msgbox "fail"
end if
Case 3:Acting as a String and explicit conversion to numeric during operation it passes
enter code here
y=inputbox("Enter a numeric value","") Rem I am using 1 as input
x=1
if Cint(y) = x then
msgbox "pass"
else
msgbox "fail"
end if
I need a logic reason for the different behaviors. but in other language it is straight forward and will work as expected
Reference: Addition Operator (+) (VBScript)
Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity. When you use the + operator, you may not be able to determine whether addition or string concatenation will occur.
The type of the expressions determines the behavior of the + operator in the following way:
If Both expressions are numeric then the result is the addition of both numbers.
If Both expressions are strings then the result is the concatenation of both strings.
If One expression is numeric and the other is a string then an Error: type mismatch will be thrown.
When working with mixed data types it is best to cast your variables into a common data type using a Type Conversion Function.
I agree with most of what #thomas-inzina has said but the OP has asked for a more detailed explanation so here goes.
As #thomas-inzina point's out using + is dangerous when working with strings and can lead to ambiguity depending on how you combine different values.
VBScript is a scripting language and unlike it's big brothers (VB, VBA and VB.Net) it's typeless only (some debate about VB and VBA also being able to be typeless but that's another topic entirely) which means it uses one data type known as Variant. Variant can infer other data types such as Integer, String, DateTime etc which is where the ambiguity can arise.
This means that you can get some unexpected behaviour when using + instead of & as + is not only a concatenation operator when being used with strings but also a addition operator when working with numeric data types.
Dim x: x = 1
Dim y: y = "1"
WScript.Echo x + y
Output:
2
Dim x: x = "1"
Dim y: y = "1"
WScript.Echo x + y
Output:
11
Dim x: x = 1
Dim y: y = 1
WScript.Echo x + y
Output:
2
Dim x: x = 1
Dim y: y = "a"
WScript.Echo x + y
Output:
Microsoft VBScript runtime error (4, 5) : Type mismatch: '[string: "a"]'

VBS convert string to floating point

Dim strnumber
strnumber = "0.3"
Dim add
add = 0.1
Dim result
result = strnumber + add
MsgBox result
I want to get 0.4 as result, but get 3.1.
I tried clng(strnumber) and int(strnumber), nothing works. There is a simple solution for sure but I won't find it.
EDIT: Solution
result = CDbl(Replace(strnumber,".",",") + add
Has to do with your locale settings. Automatic conversion (as well as explicit one) observes it in the same manner as in CStr() function.
E.g. in my locale CStr( 0.3) results to 0,3 that is invert to CDbl("0,3") while CDbl("0.3") results to an error.
BTW: always use option explicit and, for debugging purposes, On Error Goto 0
Following below procedures can help:
Replacing the dot(".") with comma (",") in the string
change the string to double by Cdbl
example:
dim a,b,c
a="10.12"
b="5.05"
a=Replace(a,".",",")
b= Replace(b,".",",")
c=Cdbl(a)+Cdbl(b)
msgbox c
You want to add two numbers. So you should use numbers (and not a string (strnumber) and a number (add):
>> n1 = 0.3
>> n2 = 0.1
>> r = n1 + n2
>> WScript.Echo r
>>
0,4
As you can see from the output (0,4), I'm using a locale (German) that uses "," as decimal 'point'. But literals always use ".". So by using the proper data types you can write your scripts in a language/locale independent fashion as long as you don't need to process external string data (from a file or user input). Then you have to modify the input before you feed it to a conversion function like CDbl(). For simple cases that can be done with Replace(inp, badmarker, goodmarker).
P.S. You said you " tried clng(strnumber) and int(strnumber)". You should have tried CDbl(). CLng() tries to get a long integer (cf. CInt()), Int() removes/rounds the fraction from number.

How to Find Record Set Value is Number or String?

Original:
Using VB6
If rsCardEvent(4).Value = Str Then
TimOut = rsCardEvent(4)
Else
TimeOut = Left(TimOut, 2) & ":" & Mid(TimOut, 3, 2) & ":" & Right(TimOut, 2)
End If
Getting Type MisMatch Error.
How To Find Record Set Value is String or Number
Exactly i need
If Number means print number like Time Format (HH:MM:SS)
else
print string value
Coding Help for the above condition
Edited Version:
I'm working with an ADO.Recordset object and am trying to determine the data type of a column at run-time. I need to handle the column value differently in my code depending on its underlying data type. If the column value is a string, I want to work with the value as-is. If it is a number, I want to treat the number as an packed time and convert it to HH:MM:SS format (i.e. the number 120537 would be converted to the string "12:05:37").
Below is some example code that demonstrates what I want to achieve. However, when I run this code I get a "Type Mismatch" error:
If rsCardEvent(4).Value = Str Then
TimOut = rsCardEvent(4)
Else
TimeOut = Left(TimOut, 2) & ":" & Mid(TimOut, 3, 2) & ":" & Right(TimOut, 2)
End If
Have a look at the Visual Basic 6 function library. There are functions that can help you determine the underlying type of a value.
There are quite a few but you might find these useful:
IsNumeric
IsDate
Based on this article, if rsCardEvent is an ADO recordset, you could check the Type property. Something like this:
Select Case rsCardEvent(4).Type
Case adBSTR, adChar, adVarChar, adWChar, _
adVarWChar, adLongVarChar, adLongVarWChar
' It is a string '
Case Else
' It is not a string '
End Select
You can use the IsNumeric function available in VB6.
How about:
If TypeName(rsCardEvent(4).Value) = "String" then
http://msdn.microsoft.com/en-us/library/5422sfdf.aspx

Resources