Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 888
Jeff Avatar asked Jul 19 '11 03:07

Jeff


1 Answers

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.

like image 145
Moe Sisko Avatar answered Oct 14 '22 04:10

Moe Sisko