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. Using ToString("C") gives me $999.00 which is not what I want.
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. 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". Otherwise it will perform an integer division. e.g :
int originalValue = 80;
string yourValue = (originalValue / 100m).ToString("C2");
This will set yourValue to "$0.80". If you leave out the "m", it will set it to "$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.
Just divide by 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. E.g: 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!
精彩评论