Remove extra zeros

rwallacej
rwallacej used Ask the Experts™
on
Hi

How do I remove "extra" zeros from end of string
e.g. replace 2.3100 with 2.31 and 4.4400000 with 4.44
(I don't simply want to round the number, rather remove extra 0's)

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
i would start at the end of the string lopping off a character at a time until i got to a non-zero character.
There are probably better ways, but this would work.
Luis PérezSoftware Architect in .Net

Commented:
Dim s As String = "4.4400000"
s = s.TrimEnd("0") 'Now trailing zeros are removed, string contains "4.44"

Hope that helps.
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Author

Commented:
thanks,

this is ok sometimes but when the value is e.g.    40 it is changed to "4", or 1000 it is changed to "1"

I don't want the number to change just remove extra decimal "0"

Author

Commented:
example please?  I can't see how the trim will remove extra zeros only after decimal points
Commented:
This should work to remove extra zeroes:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        MsgBox(FormatString("23.45600000"))
    End Sub
    Private Function FormatString(ByVal StringVal As String) As String
        Dim dbl As Double
        Double.TryParse(StringVal, dbl)
        Return dbl.ToString("g")
    End Function
End Class

Open in new window

x77

Commented:
try this function - NormalizeDouble.
Function NormalizeDouble(ByVal s As String) As String
    Dim v As Double
    If Double.TryParse(s, v) Then s = v.ToString("g")
    Return s
End Function

Open in new window

Senior Software Engineer
Commented:
As an alternative, you can use:

       Dim temp as string = Regex.Replace("2.3100000", "(\.?[0]+$)", "")

Open in new window


You need to add at top of your code file:

Imports System.Text.RegularExpression

Author

Commented:
thanks all

Commented:
Did you try the solution I posted?

Author

Commented:
no,  I hadn't tried this, a long article and other solution worked - this may have worked, too

Commented:
It was not long! It was only:

string.Format("{0:G29}", decimal.Parse("2.0044"))
or
decimal.Parse("2.0044").ToString("G29")
or
2.0m.ToString("G29")

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial