Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to Currency format, with no periods (or commas)

Tags:

string

c#

given value = 2 or 4.00
the below statement outputs

value = Convert.ToDecimal(value).ToString("C2");

value = $2.00, or $4.00

if I have value = 1000 then output will be $1,000.00 but I require $1000.00.

I don't prefer string concatenation of "$" and value.

like image 948
InfantPro'Aravind' Avatar asked Jun 29 '12 12:06

InfantPro'Aravind'


2 Answers

var stringValue = Convert.ToDecimal(value).ToString("$0.00");

As noted by @James below, this hard-codes the currency into the format. Using the format C2 will use the system currency format. This can be changed for the system (e.g. in Windows 7 - Start - Control Panel - Change Display Language - Additional Settings - Currency - Digit grouping) and will allow the C2 format to display the currency value without the comma when running on that particular system.

EDIT

All credit to @James for using the current culture. My only modification to his answer would be to clone the current NumberFormat so as to get all the properties of the current culture number format before removing the CurrencyGroupSeparator.

var formatInfo = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
formatInfo.CurrencyGroupSeparator = string.Empty;

var stringValue = Convert.ToDecimal(value).ToString("C", formatInfo);
like image 143
Kevin Aenmey Avatar answered Nov 03 '22 00:11

Kevin Aenmey


You should use the NumberFormat class to specify the type of formatting you need, ToString takes an IFormatProvider parameter e.g.

var formatInfo = (System.Globalization.NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
formatInfo.CurrencyGroupSeparator = ""; // remove the group separator
Console.WriteLine(2.ToString("C", formatInfo));
Console.WriteLine(4.ToString("C", formatInfo));
Console.WriteLine(1000.ToString("C", formatInfo));

This will keep your number formatting consistent with whichever culture you are using.

like image 42
James Avatar answered Nov 02 '22 23:11

James