I am trying to port a VB function to VB.NET, but I cannot get the function to work correctly and update properly.
rFormat = Format(Format(Value, fmt), String$(Len(fmt), "@"))
It seems like the problem lies with the String$() function parameter which is used to align decimal points of values. How would I be able to properly fix this, or is there another way to achieve this?
EDIT
The following is an example console application that shows the issues that I am having.
Imports Microsoft.VisualBasic
Module Module1
Sub Main()
Dim rFormat As String
Dim fmt As String
Dim value As Object
fmt = "########.000"
value = 12345.2451212
'value = 12345
'~~~~~~~~~~~~~~~~~~~~~
'rFormat = Microsoft.VisualBasic.Format(Microsoft.VisualBasic.Format(value, fmt), "".PadLeft(fmt.Length, "@"c))
'Console.WriteLine(rFormat) ' <<Not working prints all "@" for any value!>>>
'rFormat = Microsoft.VisualBasic.Format(Microsoft.VisualBasic.Format(value, fmt), "".PadLeft(fmt.Length))
'Console.WriteLine(rFormat) '<<Not working prints nothing>>
'rFormat = (String.Format(value, fmt)).PadLeft(Len(fmt))
'Console.WriteLine(rFormat) ' <<Not working prints the value 12345.2451212>>> should print>>>>> 12345.245
'for integer values< works good>
rFormat = String.Format("{0," + fmt.Length.ToString + "}", String.Format(value, fmt))
Console.WriteLine(rFormat) ' <<Not working prints the value 12345.2451212>>> should print>>>>> 12345.245
'for integer values< works good>
End Sub
End Module
All String$ does is repeat the character specified in the second parameter the number of times specified in the first parameter.
So if fmt is, for example "9999", then the String$ command will produce "@@@@".
You can replace this with the String.PadLeft method and continue to use the VB Format function from the Microsoft.VisualBasic namespace:
rFormat = Microsoft.VisualBasic.Format(Microsoft.VisualBasic.Format(value, fmt), "".PadLeft(fmt.Length, "@"c))
EDIT:
Based on the edit in the question, the correct format logic should be:
rFormat = String.Format("{0:" & fmt & "}", value)
It is very helpful to review the String.Format documentation since it has a lot of examples and explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With