[英]C# thousand separator issue with decimal.tryparse
我不確定這是如何在C#中正確解析的,但我希望它失敗的地方是逗號沒有分隔每個可重復的三個值。 示例:1,123.23應該通過,但11,23.23應該在我看來失敗。 但實際輸出是tryparse似乎總是返回true,無論逗號的位置在十進制之前的位置。
編輯:正在接受正則表達式的答案,因為發現這是一個錯誤。 謝謝。
string price = "1,1,2,3.23";
decimal outputValue = 0;
var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);
if (Decimal.TryParse(price, allowedStyles, CultureInfo.GetCultureInfo("EN-us"), out outputValue))
{
Console.WriteLine("Pass");
}
正如您所注意到的NumberStyles.AllowThousands
不會強制逗號位於正確的位置。 所以我認為正則表達式可以幫助你:
Regex.IsMatch("11,23.23", "^[+-]?[0-9]{1,3}(,[0-9]{3})*(.[0-9]*)?$");
我不知道這是否有幫助,但是,我想我應該嘗試一下。 我認為我的答案有點但很直接,如果關注的是格式,我在.ToString上進行比較(“格式指定”); 並將其與您的“價格”字符串進行比較。 只需2美分。
string price = "1,1,2,3.23";
decimal priceParse = 0;
if (decimal.TryParse(price, out priceParse))
{
string shouldBeFormat = Convert.ToDecimal(priceParse).ToString("#,##0.00");
if (price == shouldBeFormat)
{
// your good
}
else
{
// no good
}
}
你發現的顯然是一個錯誤。 我強烈建議不要卡在這里,而是實施一個解決方法。 (並且還申請KISS)。
除非這個代碼部分在高數學算法的核心或任何其他方式中執行數萬億次,這對於性能至關重要,這里有一個簡單的解決方法。
(假設字符串使用','(逗號)作為千位分隔符。(並且它們不是小數分隔符,因為它可能是一些文化)):
price = price.Replace(",",""); // This will not change the value when comma is thousand separator.
// Go forward to parsing
您有兩種可接受的格式,因此您可以檢查該號碼是否可解析,如果是,請檢查它是否采用可接受的格式:
string price = "1,123.23";
decimal outputValue = 0;
var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);
var cul = CultureInfo.GetCultureInfo("EN-us");
if (decimal.TryParse(price, allowedStyles, cul, out outputValue))
{
if (outputValue.ToString("N", cul) == price || outputValue.ToString("G", cul) == price)
{
Console.WriteLine("Pass");
}
}
我運行了幾個不同的代碼,我意識到當你應用AllowThousands時,','的唯一約束是它應該在數字的整數部分。
一些結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.