views:

76

answers:

1

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 ();
    }
}
+1  A: 

Actually, the easiest way would be to use ToString("N2"); where 2 is replaced by the number of decimal places you want.

If you really want minimum and maximum, you could also use IFormattable's ToString("#,#.00##", CultureInfo.CurrenCulture); which would give you a number with a minimum of two decimal places and a maximum of four, with comma digit separators on the integral part.

R. Bemrose
But how does that respect Minimum and Maximum? That's just setting Maximum.
Frank Krueger
I've updated my answer to address your comment.
R. Bemrose
(1) Object doesn't have a 1 arg ToString method. (2) Min and Max change at run time. That's what my code is doing. Please read the question, I am looking for confirmation that this is the right format string to replicate DecimalFormat.
Frank Krueger
Object doesn't have a 1-arg ToString method, but all the number classes do. And `IFormattable` has a 2-arg version, which is the same as the number classes 1-arg version with `CultureInfo.CurrentCulture` passed as the second value.
R. Bemrose