Search code examples
vb.nettrim

How to get TrimEnd() to stop at a specific character


I have a series of percentage values saved in a database that look something like this:

Percentage
_____________
100.00000
50.00000
74.02500

When I display the values to the screen, I'd like to trim unnecessary zeroes from the end of the string along with the decimal point so the above examples become:

Percentage
_____________
100
50
74.025

I'm currently using the following code:

displayVal = rawVal.TrimEnd({"0"c, "."c})

but this code continues to trim after the decimal if there are additional zeroes. I also tried:

displayVal = rawVal.TrimEnd(New String({"0", "."}))

which almost works. It just leaves the decimal point.

Is there a way to do what I want using TrimEnd() or do I need to switch to regex?


Solution

  • As Tim already mentioned in the comments, if the data type in the DB is already some numerical type, it would be best to keep it in that type and then use the appropriate numeric formatting when converting it to a string for output. If, however, the input data is already a string, then that's not an option. In that cast, the simplest option is to just do two trims in series, like this:

    Private Function RemoveUnecessaryZeros(input As String) As String
        Return input.TrimEnd("0"c).TrimEnd("."c)
    End Function
    

    However, that doesn't give you a lot of flexibility, it doesn't remove preceding zeros, and it does nothing to reformat the string using the current culture. If that matters, you could instead parse the value into a numeric type and then use the desired string formatting options to re-output it to a string. For instance:

    Private Function RemoveUnecessaryZeros(input As String) As String
        Dim result As Double
        If Double.TryParse(input, result) Then
            Return result.ToString()
        Else
            Return input
        End If
    End Function
    

    However, when you do it that way, you may potentially lose precision along the way, depending on the input numbers and the data type you choose to parse it with. If you need more control over the parsing/reformatting and you want to keep it purely in strings so no precision is lost, then you may want to consider using regex. For instance:

    Private Function RemoveUnecessaryZeros(input As String) As String
        Dim m As Match = Regex.Match(input, "[1-9]\d*(\.([1-9]|0+[1-9])+)?")
        If m.Success Then
            Return m.Value
        Else
            Return input
        End If
    End Function