CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2012
    Location
    United States
    Posts
    4

    How would I make a Parse Currency Function?

    Hey guys how would I make a parse currency function ( I think thats what it would be called) so that for example: 500k = 500,000 and that 5m = 5,000,000


    Thanks, Alex

  2. #2
    Join Date
    Jun 2012
    Posts
    10

    Re: How would I make a Parse Currency Function?

    Hey,

    I'm a noob programmer so this is likely to be off the mark, but at-least I can do a bit of learning and maybe even help the odd person if I pickup any questions that I think I can answer.

    I'm not sure what you're trying to do but I knocked this up, if it's that you're trying to define your own custom abbreviations for stuff. I think that c# uses decimal for currency, else I'd have tried to work in generics, which I've been learning.

    Somebody will likely come along and wipe this away in one line of code, but that gives me a chance to learn too!

    public static decimal ParseCurrency(string Value)
    {
    //dictionary to hold abbreviations
    Dictionary<char, string> _abbreviationMap = new Dictionary<char, string>();
    //add some abbreviations
    _abbreviationMap.Add('M', "00000");
    _abbreviationMap.Add('K', "00");
    _abbreviationMap.Add('X',"00000000");

    //validate Value
    if (!_abbreviationMap.ContainsKey(Value.Last()))
    {
    throw new Exception(string.Format("{0} is not an acceptable abbreviation.", Value.Last()));
    }

    //try parse
    decimal _result = new decimal();
    if (decimal.TryParse(Value.Substring(0, Value.Length - 1) + _abbreviationMap[Value.Last()], out _result))
    {
    return _result;
    }
    else
    {
    throw new Exception(string.Format("{0} could not be parsed."));
    }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured