簡體   English   中英

運行 Azure DevOps 構建管道時自定義文化不適用

[英]Custom Culture not applying when running an Azure DevOps build pipeline

我正在嘗試創建一個 function ,它將表示數字的字符串轉換為自定義貨幣格式。 我需要反轉分隔符(將逗號轉換為點,將點轉換為逗號)並在前面添加 $ 符號。

輸入格式示例: “70000.50”

示例 output 所需格式: “$ 70.000,50”

我的 function 是這個

    public static string ToCurrencyFormat(this string str)
    {
        if (!string.IsNullOrEmpty(str))
        {
            str = $"$ {Convert.ToDecimal(str, new CultureInfo("en-US")):N2}";
        }

        return str;
    } 

這個 function 在我的電腦上工作正常。

問題是,當我在 Azure DevOps 的構建管道中運行此 function 的測試時,測試失敗並出現以下錯誤:

Error Message:
Expected member Body[2] to be
"Value: $ 70.000,00", but
"Value: $ 70,000.00" differs near ",00" (index 12).

似乎與我指定的文化不同的文化被用於轉換小數點。

有人告訴我,我應該更改服務器中的文化,或者我的應用程序的 dockerfile。

我的問題是:

為什么 function 在 Azure DevOps 中運行時無法使用“en-US”作為區域性?

為什么服務器/dockerfile 文化優先於我指定為參數的文化?

好的,所以這里有一點要通過。 首先,不清楚為什么您的輸入是字符串而不是數字。 如果它必須是一個字符串,讓我們將其轉換為數字的步驟分開。 在您的示例代碼中,這是您專門設置文化的唯一階段。

/// <summary>
/// Note this is really just a wrapper around TryParse (so needless) but perhaps you do other
/// processing at this stage (undocumented)
/// </summary>
/// <param name="stringForm"></param>
/// <returns></returns>
public static bool ParseNumber(string stringForm,out decimal result)
{
   //Allow leading currency, decimal point, thousands separator - in your example the input number 
   // ONLY contains a decimal separator, in which case you don't need the other two styles.
   var style = NumberStyles.AllowCurrencySymbol 
     | NumberStyles.AllowDecimalPoint 
     | NumberStyles.AllowThousands;

   //You don't specify whether the incoming string has a culture.. it might, although - again - 
   // in the example you gave it looks like it's really a number and not a string at all.  
   // If you know the culture, use `new CultureInfo()` here
   if (!decimal.TryParse(stringForm, style, CultureInfo.InvariantCulture, out result)) return false;

   //Do other things with the number
   
   return true;
}

現在按照您的要求格式化數字.. 使用C格式也可以為我們提供貨幣指標。

public static string FormatForCurrency(decimal number)
{
   var format = new NumberFormatInfo
   {
      CurrencySymbol = "$",
      CurrencyDecimalSeparator = ",",
      CurrencyDecimalDigits = 2,
      CurrencyGroupSeparator = "."
   };
   return number.ToString("C", format);//$70.000,50
}

如果您必須有基於字符串的數字,那么要將它們一起使用,您將使用如下代碼:

public static string UseStringNumberAndFormatAsCurrency(string numberAsString)
{
   if (!ParseNumber(numberAsString, out var num))
   {
      //You may want to throw an exception instead, you could also consider `decimal.Parse`
      // instead of `decimal.TryParse` for this
      Console.WriteLine("Invalid string number: ", numberAsString);
      return null;
   }
   return FormatForCurrency(num);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM