简体   繁体   English

将小数点格式设置为次要货币

[英]Format a decimal to a minor currency

I need to format a decimal to a minor currency eg 10.00 should be 1000. 我需要将小数格式化为次要货币,例如10.00应该是1000。

decimal currency = 10.00m;
System.Console.WriteLine(currency.ToString("######"));

Produces 10, how do I get the decimal points to be added to that? 产生10,如何获得要加的小数点?

解决方案非常简单

* 100

I would create an extension method like this that would produce always the expected result, with the required number of decimals: 我将创建一个像这样的扩展方法,它将始终产生期望的结果,并带有所需的小数位数:

public static class DecimalExtension
{
    public static string FormatAsMinorCurrency(this decimal value) {
        var numberFormat = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
        numberFormat.CurrencyDecimalDigits = 2;
        numberFormat.CurrencyDecimalSeparator = ".";
        numberFormat.CurrencySymbol = "";
        numberFormat.CurrencyGroupSeparator = "";
        return value.ToString("c", numberFormat).Replace(".", "");
    }
}

The results: 结果:

1.FormatAsMinorCurrency() 
100

10.FormatAsMinorCurrency()
1000

1000000.34102350915091M.FormatAsMinorCurrency()
100000034

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM