2017-11-07 14 views
1

제가 적용 특정 CultureInfo에 번호를 정상화하려고 사투를 벌인거야 10 진수가 포함 된 문자열의 NumberFormat표준화 특정 CultureInfo.NumberFormat

의 내가 일부 문자가 포함 된 문자열을 있다고 가정 해 봅시다, 그래서 그것을 청소해야합니다 그래서 기본적으로 ,'. 유지하고있어

var cleanedInput = Regex.Replace(userInput, @"[^0-9-,'.]+", ""); 

합니다. 나는 CultureInfo에 따라 ,.이 십진법을 분리하거나 숫자를 그룹화하는 데 다르게 사용되기 때문에이 작업을 수행하고 있습니다. 그걸 염두에 데

, 나는 소수를 허용하도록 NumberStyle을 지정 Decimal.TryParse 방법을 적용하고 IFormatProvider는 dinamically CultureInfo.NumberFormat 원하는 "로컬"에 적용 할 예정이다.

decimal numericData; 
if (!decimal.TryParse(cleanedInput, NumberStyles.AllowDecimalPoint, LocaleUser.NumberFormat, out numericData)) 
    throw new Exception($"Error occurred. Could not parse:{cleanedInput} "); 

"hi9000,99hi"을 입력한다고합시다. 일단 청소하면 "9000,99"이됩니다. 좋은. 그렇다면 TryParse을 적용하고 Decimal9000.99을 반환합니다. 중요한 것은 실제로 es-ESCultureInfo을 적용하고 있으며 소수점 구분자로 ,을가집니다. 나는 기본적으로 9000,99 또는 9.000,99을 기대하고 있습니다.

코드는 Exception을 발생시키지 않지만 지정된 CultureInfo을 적용하지 않는 것 같습니다.

정확히 무엇이 누락 되었습니까? 나는 Decimal.TryParse이 내가 잘 다루는 스위스 육군 칼이라는 느낌을 가지고있다.

미리 감사드립니다.

+2

나는 문제가 무엇인지 정확히 모르겠지만, 소수가 형식을 _have_되지 않는다는 점에 유의해야합니다. 값을 표시 할 때 형식을 제공합니다. 디버거에서보고있는 경우 컴퓨터가 설정된 문화권을 사용합니다. 값을 특정 형식으로 보려면'decimal.ToString' 또는'string.Format'을 사용하십시오. –

+1

명확히하기 위해 제공하는 코드에서 예외가 발생하고 있습니까? 그리고'cleanedInput'은 파서에 가기 전에 당신이 기대하는 것입니까? –

+0

답장 보내 주셔서 감사합니다. 이 코드는 예외를 발생시키지 않지만, 내가 얻은 결과는 내가 지정한 CultureInfo를 적용하지 않고, 디버깅중인 VS2015를 사용하는 CultureInfo조차도 적용하지 않는다. – Gonzo345

답변

0

double.Parse, decimal.Parse 또는 decimal.TryParse를 사용하면 효과가있는 것 같습니다. CultureInfo는 어떻게 정의 되었습니까?

string value = "9000,99"; 
decimal number; 
CultureInfo culture = CultureInfo.CreateSpecificCulture("es-ES"); 

try { 
    number = decimal.Parse(value, culture); 
    decimal.TryParse(value, NumberStyles.Any, culture, out decimal num); 
    Console.WriteLine($"{culture.Name}: {value} = {number}/{num}");      
} catch (FormatException) { 
    Console.WriteLine($"{culture.Name}: Unable to parse [{value}]"); 
} 

출력 :

es-ES: 9000,99 = 9000.99/9000.99 
+0

마침내 내가 잘못하고있는 것을 얻었고 실제 컴퓨터의 CultureInfo에 의해 "수정 된"최종 출력물을 해석하고있었습니다. BTW, CultureInfo는 prop에 의해 지정되었습니다. :) – Gonzo345

0

그래서, 진수는 항상 진수하고 진술 된 의견에로, 어떤 형식이 없다는 것을 주어, 내가 잘못 질문에 초점을 맞추고 제가이었다 검색!

나는 마지막으로이 방법을 사용하고 있습니다 :

private decimal CleanUserInput(string userInput, CultureInfo localeUser) 
{ 
    if (localeUser == null) 
     throw new Exception("A CultureInfo must be specified. "); 

    var cleanedInput = Regex.Replace(userInput, @"[^0-9-,\.']+", ""); 
    if (string.IsNullOrWhiteSpace(cleanedInput)) 
     throw new Exception("Data provided has no numbers to be parsed. "); 

    decimal numericData; 
    if (!decimal.TryParse(cleanedInput, NumberStyles.Any, localeUser, out numericData)) 
     throw new Exception($"Couldn't parse {cleanedInput} . Make sure the applied CultureInfo ({LocaleUser.DisplayName}) is the correct one. Decimal separator to be applied: <{LocaleUser.NumberFormat.NumberDecimalSeparator}> Numeric group separator to be applied: <{LocaleUser.NumberFormat.NumberGroupSeparator}>"); 

    return numericData; 
}