שתף באמצעות


How to convert a percentage to a double?

Question

Tuesday, August 13, 2013 3:40 PM

Hello,

I was wondering if there is a way to convert a percentage (such as 94.75%) to a double, without running through major string manipluation.

Thanks, Jeffrey

Jeffrey Doiron

All replies (5)

Tuesday, August 13, 2013 3:58 PM ✅Answered | 1 vote

Are you saying that you have a string "94.75%"? If so,

Dim p As String = "94.75%"
Dim d As Double = Double.Parse(p.TrimEnd("%"c))

HTH,

Andrew


Tuesday, August 13, 2013 4:03 PM ✅Answered

Hi

Well, I don't know if this is classified as major string manipluation, but it gets the job done.

        Dim pc As String = "94.23%"
        Dim v As Double = 0.0
        If pc.Contains("%") Then  pc = pc.Substring(0, pc.Length - 1)
        If Double.TryParse(pc, v) Then
            'got it, v contains double
        Else
            ' not valid percentage, v = zero
        End If

Or, if you want it as a function ........

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim pc As String = "94.23%"
        Dim d As Double = PercentToDouble(pc)
    End Sub
    Private Function PercentToDouble(pc As String) As Double
        Dim dbl As Double = 0.0
        If pc.Contains("%") Then pc = pc.Substring(0, pc.Length - 1)
        If Double.TryParse(pc, dbl) Then Return dbl
        Return 0.0
    End Function

Regards Les, Livingston, Scotland


Tuesday, August 13, 2013 4:15 PM ✅Answered | 1 vote

Jeffrey,

Did you want to simply return a double as 94.75, or did you mean 0.9475?

If the latter, use one of the code samples shown, then remember to divide by 100.

Please call me Frank :)


Tuesday, August 13, 2013 4:29 PM ✅Answered

Below are two methods (results1 & results2).  Choose your poison

Imports System.Text.RegularExpressionsModule Module1    Sub Main()        'extract number from input string        Dim input As String = "here is the percentage = 94.75%"        Dim expr As Regex = New Regex("(\d+\.\d+)\%")        Dim myMatch As Match = expr.Match(input)        Dim percentage As String = myMatch.Groups(1).Value        'method 1        Dim results1 As String        Dim position As Integer = percentage.IndexOf(".")        Select Case position            Case 0                results1 = ".00" & percentage.Replace(".", "")            Case 1                results1 = "0.0" & percentage.Replace(".", "")            Case Is >= 2                results1 = percentage.Replace(".", "")                results1 = results1.Insert(position - 2, ".")        End Select        'method 2        Dim results2 As String = (Double.Parse(percentage) / 100).ToString    End SubEnd Module

jdweng


Tuesday, August 13, 2013 4:32 PM

If the latter, use one of the code samples shown, then remember to divide by 100.

Oops! Good point.

--
Andrew