C # Convert int to currency string with decimal places

Conversions. Blah ... perhaps the most confusing aspect of the language for me.

Anyway, I want to convert int 999 to $ 9.99. Using ToString ("C") gives me $ 999.00, which is not what I want.

All my integers will work this way, if the price of something is 12.30, the int value will be 1230. Two decimal places always. I know that it will be easy for most, I can not find anything here or through Google.

Also, any resources that you have during conversions will be very grateful!

+4
source share
3 answers

If your source variable is declared as int, then one of the possible solutions is to divide by "100 m" instead of "100". Otherwise, it will perform integer division. eg:

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

This will set yourValue to $ 0.80. If you do not specify "m", it will set the value to "0.00".

NOTE. "m" tells the compiler to treat 100 as a decimal number, and an implicit conversion will occur with originalValue as part of the division.

+14
source

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 

Strike>

See here for more details.

UPDATE:

Today I have to be troubled ... you will also have to convert to double or you will lose decimals:

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

(Alternatively, you can use decimal, since this is usually the preferred type for the currency ).

+5
source

I have a function for those who just need to split zeros based on a specific separator. For example: 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 it!

0
source

All Articles