Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a double to currency rounded to the nearest dollar?

Right now I have

double numba = 5212.6312 String.Format("{0:C}", Convert.ToInt32(numba) ) 

This will give me

$5,213.00 

but I don't want the ".00".

I know I can just drop the last three characters of the string every time to achieve the effect, but seems like there should be an easier way.

like image 230
spilliton Avatar asked May 20 '09 20:05

spilliton


People also ask

How to format currency in Excel formula?

Generally, you should use the Format Cells dialog (Ctrl+1) or Home > Number > Accounting Number Format option to apply a currency formatting to a cell.

How many decimal places do I use when changing to currency?

Currency (units of monetary value) By default, cells formatted as currency display two decimal places. You can change this setting so cells display as many decimal places as you type in them, or so all cells display the same number of decimal places.

What number format that puts a dollar symbol?

A number format that puts dollar symbols before each value by default is known as accounting format/currency format. Explanation: The number format is known as the currency format. In the format, we can use the text function.


2 Answers

First - don't keep currency in a double - use a decimal instead. Every time. Then use "C0" as the format specifier:

decimal numba = 5212.6312M; string s = numba.ToString("C0"); 
like image 139
Marc Gravell Avatar answered Sep 25 '22 05:09

Marc Gravell


This should do the job:

String.Format("{0:C0}", Convert.ToInt32(numba)) 

The number after the C specifies the number of decimal places to include.

I suspect you really want to be using the decimal type for storing such numbers however.

like image 37
Noldorin Avatar answered Sep 25 '22 05:09

Noldorin