简体   繁体   English

C# 将 int 转换为带小数位的货币字符串

[英]C# Convert int to currency string with decimal places

Conversions.转换。 Blah... possibly the most confusing aspect of the language for me.废话……对我来说可能是语言中最令人困惑的方面。

Anyways, I want to convert the int 999 to $9.99.无论如何,我想将 int 999 转换为 9.99 美元。 Using ToString("C") gives me $999.00 which is not what I want.使用 ToString("C") 给我 999.00 美元,这不是我想要的。

All of my integers will work this way meaning if the price of something is 12.30 the int value will be 1230. Two decimal places, always.我所有的整数都将以这种方式工作,这意味着如果某物的价格为 12.30,则 int 值将为 1230。始终保留两位小数。 I know this will be easy for most, I cannot find anything here or through Google.我知道这对大多数人来说很容易,我在这里或通过谷歌找不到任何东西。

Also, any resources you have on conversions would be greatly appreciated!此外,您在转换方面拥有的任何资源将不胜感激!

If your source variable is declared as an int, then one possible solution is to divide by "100m" instead of "100".如果您的源变量声明为 int,那么一种可能的解决方案是除以“100m”而不是“100”。 Otherwise it will perform an integer division.否则它将执行 integer 除法。 eg:例如:

    int originalValue = 80;
    string yourValue = (originalValue / 100m).ToString("C2");

This will set yourValue to "$0.80".这会将 yourValue 设置为“$0.80”。 If you leave out the "m", it will set it to "$0.00".如果省略“m”,它将设置为“$0.00”。

NOTE: The "m" tells the compiler to treat the 100 as a decimal and an implicit cast will happen to originalValue as part of the division.注意:“m”告诉编译器将 100 视为小数,并且将在 originalValue 作为除法的一部分进行隐式转换。

Just divide by 100:只需除以 100:

 yourValue = (originalValue / 100).ToString("C");<br> // C will ensure two decimal places... <br> // you can also specificy en-US or whatever for you currency format

See here for currency format details.有关货币格式的详细信息,请参见此处

UPDATE:更新:

I must be slow today... you'll also have to convert to a double or you'll lose your decimal places:我今天一定很慢...您还必须转换为双精度,否则您将丢失小数位:

yourValue = ((double)originalValue / 100).ToString("C");

(Alternatively, you could use decimal, since it is usually the preferred type for currency ). (或者,您可以使用小数,因为它通常是货币的首选类型)。

I got a function for anyone who just need to divide the zeroes based on certain separator.我得到了一个 function 对于任何只需要根据特定分隔符除零的人。 Eg: 1250000 -> 1,250,000..例如:1250000 -> 1,250,000..

public static string IntToCurrencyString(int number, string separator)
{
    string moneyReversed = "";

    string strNumber = number.ToString();

    int processedCount = 0;

    for (int i = (strNumber.Length - 1); i >= 0; i--)
    {
        moneyReversed += strNumber[i];

        processedCount += 1;

        if ((processedCount % 3) == 0 && processedCount < strNumber.Length)
        {
            moneyReversed += separator;
        }
    }

    string money = "";

    for (int i = (moneyReversed.Length - 1); i >= 0; i--)
    {
        money += moneyReversed[i];
    }

    return money;
}

Enjoy!享受!

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

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