Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update Format function from VB to VB.NET

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
like image 702
Matthew Avatar asked Sep 11 '26 20:09

Matthew


1 Answers

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.

like image 171
competent_tech Avatar answered Sep 14 '26 09:09

competent_tech