2010-01-05 15 views
7

C'è un modo migliore di analizzare la percentuale per raddoppiare in questo modo?Percentuale di percentuale per raddoppiare

Dim Buffer As String = "50.00%" 
Dim Value As Double = Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture)/100 
+3

Perché hard-code il simbolo di percentuale (%) quando si potrebbe utilizzare : http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.percentsymbol.aspx – rohancragg

risposta

7

Il modo in cui si sta facendo sembra buono per me .

L'unico punto su cui fare attenzione è che il programma sta assumendo InvariantCulture. Assicurati che questo sia effettivamente ciò che intendi. Ad esempio, potrebbe essere preferibile utilizzare la cultura predefinita della macchina se la stringa proviene da un input dell'utente piuttosto che da un protocollo fisso ben definito.

+0

Invariant.Culture è solo per semplicità del campione. StackOverflow non ha input da parte dell'utente per il mio codice di esempio :-) –

1

Non ho dimestichezza con VB, ma la creazione di una funzione di fuori di esso è già migliore

codice pseudo:

function PercentToDouble(Buffer) 
    return Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture)/100; 
endfunction 
3

Si potrebbe votare per questo .NET Framework 4 suggerimento su Microsoft Connect: Extend double.Parse to interpret Percent values

+1

Ho votato. Riceverò un adesivo;) – dbasnett

+0

Non mi ero reso conto di quanti anni avesse ... – dbasnett

+0

@dbasnett Triste, sembra che il suggerimento sia stato chiuso senza fissare o una spiegazione adeguata perché lo stavano chiudendo. –

0

Se la percentuale è l'input dell'utente, allora

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click 
    Dim pb As New PictureBox 
    Dim foo As New gameObj(pb, gameObjType.person) 

    Dim sInps() As String = New String() {"50.00 %", "51.00%", ".52", "53", ".54%"} 

    For Each sampleInput As String In sInps 
     Debug.WriteLine(ConvertPercentToDouble(sampleInput).ToString("n4")) 
    Next 

End Sub 

Private Function ConvertPercentToDouble(s As String) As Double 
    Dim Value As Double 
    Dim hasPercent As Boolean = s.Contains(System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol) 
    Dim whereIsPC As Integer = Math.Max(s.IndexOf(" "), _ 
             s.IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol)) 
    If Double.TryParse(s, Value) _ 
     OrElse Double.TryParse(s.Substring(0, whereIsPC).Trim, Value) Then 
     If Value > 1 OrElse hasPercent Then Value /= 100 
     Return Value 
    Else 
     Throw New ArgumentException("YOUR ERROR HERE") 
    End If 
End Function