huMpty duMpty
huMpty duMpty

Reputation: 14460

Convert currency values

I am trying to convert one currency to another

eg.

  decimal value= 0;
  var text = "£135";
  decimal.TryParse(text, NumberStyles.Any, new CultureInfo("fa-IR"), out value);

this result value as "0". Am I doing anything wrong here?

Or is there any other way of doing this?

Any help is appreciate!!!

Update

I tired

var value= string.Format(new CultureInfo("en-US"), "{0:c}", text);
then value = "£135"

var value = string.Format(new CultureInfo("en-US", false), "{0:c}", text);
then value = "£135" 

var value = string.Format(new CultureInfo("en-US", false), "{0:c}", "135");
then value = "135"

Upvotes: 1

Views: 868

Answers (2)

Justin Pihony
Justin Pihony

Reputation: 67075

You should probably do something more like this if you want the currency symbol

var s = 135.ToString("C", new CultureInfo("en-US"));

This will give you your $135.00

You can only work off of non-string values, though. So, if you want to convert them back and forth, then you will need to go from a string back to a decimal first

  var s = 135.ToString("C", new CultureInfo("en-US"));
  //$135.00
  decimal x;
  var tryParse = decimal.TryParse(s, NumberStyles.Currency, new CultureInfo("en-US"), out x);
  var s1 = x.ToString("C", new CultureInfo("fa-IR"));
  //ريال 135/00

Upvotes: 3

Pandian
Pandian

Reputation: 9126

"£135" this Contains Currency Symbol and decimal.TryParse not able to get the Symbol.. so only it returns "0" ...

Try to Pass the Value with out Symbol then it works.... other wise use string.Format in code...

decimal value= 0;
var text = "135";
decimal.TryParse(text, NumberStyles.Any, new CultureInfo("fa-IR"), out value);

Upvotes: 1

Related Questions