Skip to content

Instantly share code, notes, and snippets.

@kariudo
Last active May 5, 2017 14:26
Show Gist options
  • Save kariudo/100bd04841f18052039b9ff5e7fe6964 to your computer and use it in GitHub Desktop.
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.
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
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();
}
}
@kariudo
Copy link
Author

kariudo commented May 5, 2017

Added VB version and added NumberStyles.AllowLeadingSign so negatives convert correctly instead of going to zero

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment