gpt4 book ai didi

c# - K、M 和 B 的 String.Format 货币

转载 作者:行者123 更新时间:2023-11-30 21:59:41 25 4
gpt4 key购买 nike

如果货币金额非常大,我会尝试将其缩写。

例如:

   if (amt > 1000000)
{
decimal d = (decimal)Math.Round(amt / 1000, 0);
return String.Format("{0:C0}", d) + " K";
}

如果给定的数字超过 100 万,它将去掉最后 3 位数字并替换为 K。当货币符号(如 $ 在左侧)时工作正常

但是,一些货币符号会放在右侧。

因此,我不会用漂亮的 $100 K 换取美元,而是用 100 € K 换取法国欧元。

如何更改格式以将 K 紧跟在数字之后和货币符号之前。

这似乎有点过头了。有什么想法吗?

最佳答案

我会像这样用 IFormatProvider 创建一个类

public class MoneyFormat: IFormatProvider,  ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}

public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
if (arg.GetType() != typeof(decimal))
try
{
return HandleOtherFormats(fmt, arg);
}
catch (FormatException e)
{
throw new FormatException(string.Format("The format of '{0}' is invalid", fmt), e);
}

string ufmt = fmt.ToUpper(CultureInfo.InvariantCulture);
if (!(ufmt == "K"))
try
{
return HandleOtherFormats(fmt, arg);
}
catch (FormatException e)
{
throw new FormatException(string.Format("The format of '{0}' is invalid", fmt), e);
}

decimal result;
if (decimal.TryParse(arg.ToString(), out result))
{
if (result >= 1000000)
{
decimal d = (decimal)Math.Round(result / 10000, 0);

CultureInfo clone = (CultureInfo)CultureInfo.CurrentCulture.Clone();
string oldCurrSymbol = clone.NumberFormat.CurrencySymbol;
clone.NumberFormat.CurrencySymbol = "";

return String.Format(clone, "{0:C0}", d).Trim() + " K" + oldCurrSymbol;
}
}
else
return string.Format("{0:C0}", result) + " K";
}

private string HandleOtherFormats(string format, object arg)
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
else if (arg != null)
return arg.ToString();
else
return string.Empty;
}
}

然后你可以像这样以你的格式调用它:

return string.Format( new MoneyFormat(), "{0:K}", amt);

然后您可以调整您想要表示“K”或其他要添加的引用符号的方式

文化信息(“fr-fr”):10 万欧元

文化信息(“en-us”):100 千美元

文化信息(“ru-RU”):100 Kр。

关于c# - K、M 和 B 的 String.Format 货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29091240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com