0

How to add decimal point (with two decimal places) to string, without converting string to decimal?

For example (Dim str1 as String), regardless str1 has value: 100 , 100.0 , 100.00, or 100.5 , 100.50... I'd like to get the output: 100.00 or 100.50, with two decimal places.

Renatas M.
  • 11,694
  • 1
  • 43
  • 62
Mega
  • 557
  • 2
  • 10
  • 22
  • 3
    `CDec(myString).ToString("D2")` isn't so prohibitive that you should balk at it. Just cast and call `ToString`. – lsuarez Jan 17 '12 at 13:21
  • 1
    don't know vb but in c# convert it to decimal, round it up and then convert back to string http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c – dierre Jan 17 '12 at 13:23
  • I have tried with `CDec(myString).ToString("D2")`, but I got Exception error: ex.Message = "Format specifier was invalid." This is my code: `Dim str1 As String = "100.0"` `Dim str2 As String` `str2 = CDec(str1).ToString("D2")` – Mega Jan 17 '12 at 13:34

3 Answers3

1
Public Function FormatNumber(ByVal s As String) As String
    Dim pos As Integer = s.IndexOf("."c)
    If pos = -1 Then ' No decimal point
        Return s & ".00"
    Else
        Return (s & "00").Substring(0, pos + 3)
    End If
End Function

And since you inserted a C# tag:

public string FormatNumber(string s)
{
    int pos = s.IndexOf('.');
    if (pos == -1) { // No decimal point 
        return s + ".00";
    } else {
        return (s + "00").Substring(0, pos + 3);
    }
}

However, note that superfluous decimals will be truncated - no rounding occurs!

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

Can't add comment yet, so excuse the additional post...

lthibodeaux and dierre are correct. Converting to decimal and back is much better. Otherwise you could create a function that looks for a decimal point in the string and then appends zeroes to it based on where it finds it. The problem is if you get a str like "13.876". You would have to figure out how to do rounding on the string.

Go the easy route.

APrough
  • 2,671
  • 3
  • 23
  • 31
0
Public Shared Function TwoDecimalString(input As String) As String
    Dim output As String
    Dim splittedInput As String() = input.Split("."C)
    If splittedInput.Length = 1 Then
        output = input & ".00"
    Else
        output = splittedInput(0) & "." & splittedInput(1).PadRight(2, "0"C)
    End If
    Return output
End Function
Wouter Janssens
  • 1,593
  • 10
  • 17