Question

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.

Was it helpful?

Solution

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!

OTHER TIPS

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.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top