Search code examples
vb.netdecimaldecimal-point

How to include decimal point to string in vb.net?


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.


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!