Last active
May 5, 2017 14:26
-
-
Save kariudo/100bd04841f18052039b9ff5e7fe6964 to your computer and use it in GitHub Desktop.
A little fiddle to parse a decimal string in the context of multiple cultures.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports System | |
Public Module Module1 | |
Public Sub Main() | |
Console.WriteLine(Decimal.Parse("-2")) | |
Console.WriteLine(MakeDoubleGreatAgain("-3.33")) | |
End Sub | |
'Parse assorted cutlures for doubles | |
Public Function MakeDoubleGreatAgain(value As String) As Double | |
Dim style As System.Globalization.NumberStyles | |
Dim number As Decimal = 0 | |
style = System.Globalization.NumberStyles.AllowDecimalPoint Or System.Globalization.NumberStyles.AllowThousands Or System.Globalization.NumberStyles.AllowLeadingSign | |
Dim cultures() As String = {"fr-FR", "en-US", "en-GB", "es-ES"} | |
For Each culture As String In cultures | |
If [Decimal].TryParse(value, style, System.Globalization.CultureInfo.CreateSpecificCulture(culture), number) Then | |
Exit For | |
End If | |
Next | |
Return number | |
End Function | |
End Module |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Globalization; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine(MakeStringGreatAgain("2.234.234,12")); | |
} | |
public static string MakeStringGreatAgain(string value){ | |
NumberStyles style; | |
decimal number = 0; | |
style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign; | |
var cultures = new[] {"fr-FR", "en-US", "en-GB", "es-ES"}; | |
foreach (var culture in cultures) | |
{ | |
if (Decimal.TryParse(value, style, CultureInfo.CreateSpecificCulture(culture), out number)) | |
break; | |
} | |
return number.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added VB version and added NumberStyles.AllowLeadingSign so negatives convert correctly instead of going to zero