tronc
tronc

Reputation: 693

Convert decimal currency to comma separated value

I get from a webservice the following strings:

12.95

or

1,200.99

Is there an option to convert these values to the following values without manipulating the string?

12,95

or

1200,99

I tried it with some Culture options but didn't get it right...

EDIT

I tried this:

    //return string.Format( "{0:f2}", Convert.ToDecimal( price ) );
    //return string.Format(CultureInfo.GetCultureInfo("de-de"), "{0:0}", price);

                

    NumberFormatInfo format = new System.Globalization.NumberFormatInfo();

    format.CurrencyDecimalDigits = 2;
    format.CurrencyDecimalSeparator = ",";
    format.CurrencyGroupSeparator = "";

    return decimal.Parse(price).ToString(format);

Upvotes: 0

Views: 10514

Answers (5)

Joe Ratzer
Joe Ratzer

Reputation: 18549

What about something like this:

    double number;
    double.TryParse("1,200.99", NumberStyles.Any, CultureInfo.CreateSpecificCulture("en-US"), out number);
    var formattedNumber = number.ToString(CultureInfo.CreateSpecificCulture("de-DE"));

Then return or write out formattedNumber (whatever you need to do).

Upvotes: 1

brendonofficial
brendonofficial

Reputation: 910

Close enough tronc,

Try this snippet:

String curStr = "12.95";
Decimal decVal;
var valid = Decimal.TryParse(curStr, out decVal);
if (!valid) throw new Exception("Invalid format.");
String newFormat = decVal.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"));

Within the toString(...) call, you can append a number after 'C' to specify how many decimal places should follow. E.g "C3".

Upvotes: 0

Meta-Knight
Meta-Knight

Reputation: 17845

var input = "1,200.99";

//Convert to decimal using US culture (or other culture using . as decimal separator)
decimal value = decimal.Parse(input, CultureInfo.GetCultureInfo("en-US"));

//Convert to string using DE culture (or other culture using , as decimal separator)
string output = value.ToString(CultureInfo.GetCultureInfo("de-DE"));

Console.WriteLine(output); //1200,99

Upvotes: 7

Rahul Tripathi
Rahul Tripathi

Reputation: 172418

You may try for something like this:

String.Format("{0:#,###0}", 0);

or may be like this:

string str = yourNumber.Remove(",").Replace(".",",");

Upvotes: 0

Andrew Ring
Andrew Ring

Reputation: 3343

Yes and no. First, what you have is a string, and so you cannot change the formatting of it as you're attempting to. However, to achieve what you would like, you can parse the string into a decimal value and then use the formatting options for decimals to display it in any reasonable way.

Upvotes: 0

Related Questions