Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Currency string to Integer?

I have a string with currency format like $35.00 and this has to be converted to 35.

Is that possible to retrieve using String.Format{ }

like image 829
Prabhakaran Avatar asked Nov 04 '10 06:11

Prabhakaran


People also ask

How do I format currency in numbers?

On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want.

How do you format a currency field?

Right-click the date field, and then click Properties. In the Property Sheet, select the format you want from the Format property list.

What is the Tostring format code for currency?

The "C" (or currency) format specifier is used to convert a number to a string representing a currency amount. Let us see an example. double value = 139.87; Now to display the above number until three decimal places, use (“C3”) currency format specifier.


1 Answers

int value = int.Parse("$35.00", NumberStyles.Currency);

Should give you the answer you need.

However, a value like $35.50 converted to an integer will likely not return what you want it to, as Integers do not support partial (decimal) numbers. You didn't specify what to expect in that situation.

[EDIT: Changed double to decimal which is safer to use with currency]

If you want to get a value of 35.5 in that situation, you might want to use the decimal type.

decimal value = decimal.Parse("$35.00", NumberStyles.Currency);

Note that you have to be very careful when dealing with money and floating point precision.

like image 172
Khalos Avatar answered Sep 18 '22 17:09

Khalos