Replicating Java's DecimalFormat in C#

Posted by Frank Krueger on Stack Overflow See other posts from Stack Overflow or by Frank Krueger
Published on 2010-05-27T19:29:43Z Indexed on 2010/05/27 19:31 UTC
Read the original article Hit count: 283

Filed under:
|
|
|

I am trying to replicate a subset of Java's DecimalFormat class. Below is what I've come up with. Does this look right to everyone?

public class DecimalFormat : NumberFormat
{
    int _maximumFractionDigits;
    int _minimumFractionDigits;

    string _format;

    void RebuildFormat ()
    {           
        _format = "{0:0.";

        _format += new string ('0', _minimumFractionDigits);
        if (_maximumFractionDigits > _minimumFractionDigits) {
            _format += new string ('#', _maximumFractionDigits -
                         _minimumFractionDigits);
        }

        _format += "}";
    }

    public override string format (object value)
    {
        return string.Format (_format, value);
    }

    public override void setMaximumFractionDigits (int n)
    {
        _maximumFractionDigits = n;
        RebuildFormat ();
    }

    public override void setMinimumFractionDigits (int n)
    {
        _minimumFractionDigits = n;
        RebuildFormat ();
    }

    public override void setGroupingUsed (bool g)
    {
    }

    public static NumberFormat getInstance ()
    {
        return new DecimalFormat ();
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about java