Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format vs int.ToString in regards to iCustomFormatter issue

I have the following two lines of code:

var BadResult = (100).ToString("B", new CustomFormatter ());
var GoodResult = String.Format("{0}", 100, new CustomFormatter ());

Whereas, BadResult obviously is bad, and GoodResult is good. My CustomFormatter class is declared like this: (also, with the one function I feel is relevant):

public class CustomFormatter 
               : IFormatProvider, ICustomFormatter
{
    public virtual Object GetFormat(Type formatType)
    {
        String formatTypeName = formatType.ToString();
        formatTypeName = formatTypeName;
        Object formatter = null;
        if (formatType == typeof(ICustomFormatter))
            formatter = this;
        return formatter;
    }
}

The issue itself, when I run the line of code with "good result", the GetFormat function is requestng an instance of CustomFormatter.

Whenever its called with Float.Tostring(), its expecting an instance of NumberFormatInfo.

I initially jumped to "my CustomFormatter should be deriving from NumberFormatInfo". Unfortunately, the class is sealed.

So: What do I need to do to be able to call Float.ToString() with a custom formatter?

Thanks!

like image 501
greggorob64 Avatar asked Oct 09 '22 07:10

greggorob64


1 Answers

Your

 var GoodResult = String.Format("{0}", 100, new CustomFormatter ());

is not using the CustomFormatter. So your good results seems to be achieved by the defaults.

What you want is probably:

 var GoodResult = String.Format(new CustomFormatter (), "{0}", 100);

See how that works.

like image 149
Henk Holterman Avatar answered Oct 12 '22 20:10

Henk Holterman