我无法将此 JS 函数转换为 C#。找不到 isNan 和 ||取代

I am unable to convert this JS Function to C#. Can't find isNan and || to replace

js代码为:

var thousand = ',';
var decimal = '.';
var decimalPlaces = 2;

function formatMoney(number, places, symbol, thousand, decimal, Alignment) {
    symbol = '$';
    number = number || 0;
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "$";
    if (typeof thousand == 'undefined' || thousand == null) {
        thousand = ",";
    }

    decimal = decimal || ".";
    var negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    if (typeof Alignment != 'undefined' && Alignment != null && Alignment.toLowerCase() == "right") {

        return negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "") + symbol;
    }
    else {
        return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    }
}

所以我想在 C# 中编写此代码 我曾尝试使用 Parse 替代 isNan,但我无法为 || 做

||运算符在 C# 中不可用于设置变量(我想这就是它需要替换的地方)。因此,您只需检查该值(例如 number = (number == null) ? 0 : number;)。

对于 isNaN,您可以创建如下函数:

public bool IsNumeric(string value)
{
     return value.All(char.IsNumber);
}

并用它来检查某物是否是数字。

希望对您有所帮助!

你不必担心 undefined 就好像它是你函数的参数一样,它总是被定义的,否则编译器会在 运行 之前给出错误。 Javascript 是不同的,因为你可以定义一个参数而不传递任何东西给函数。 你必须说例如

 public string formatMoney(int number, string places,string  symbol,string  thousand,string  decimal,string  Alignment)

所以千总是被定义

你只需要更换:

if (typeof thousand == 'undefined' || thousand == null)

if(String.IsNullOrWhitespace(thousand))

如果千是字符串

如果 number 在您的 C# 代码中可以为空(例如 decimal?),您可以使用 null-coalescing 运算符替代 ||:

number = number ?? 0;

由于 C# 是一种强类型语言,您不必担心像在 JS 中那样传递任意类型。您可以将 places 参数声明为 int?,然后只需执行以下操作:

places = places.HasValue ? Math.Abs(places.Value) : 2;

你也应该介意,standard and custom formatting in C#, including a specific currency format specifier已经有很多内置函数,所以你可能想看看那个。

示例:

static string FormatMoney(decimal number, int places, string symbol, string thousand, string @decimal, int alignment)
{  
    var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
    nfi.CurrencyGroupSeparator = thousand;
    nfi.CurrencyDecimalSeparator = @decimal;
    nfi.CurrencyDecimalDigits = places;
    nfi.CurrencySymbol = symbol;
    nfi.CurrencyPositivePattern = alignment;
    return number.ToString("C", nfi);
}

decimal value = 123456.789m;
Console.WriteLine(FormatMoney(value, 2, "$", ",", ".", 0));

// OUTPUT:
// 3,456.79