Custom IFormatProvider

The following example shows how to write a custom IFormatProvider which you can use in methodString.Format(I­FormatProvider, …).

This formatter formats doubles to 3 decimal places with a dot separator.

[C#]

public class DoubleFormatter : IFormatProvider, ICustomFormatter
{
// always use dot separator for doubles
private CultureInfo enUsCulture = CultureInfo.GetCultureInfo("en-US");
 
public string Format(string format, object arg, IFormatProvider formatProvider)
{
// format doubles to 3 decimal places
return string.Format(enUsCulture, "{0:0.000}", arg);
}
 
public object GetFormat(Type formatType)
{
return (formatType == typeof(ICustomFormatter)) ? this : null;
}
}

Having this formatter, we can use it like this:

[C#]

double width = 15.77555;
double height = 12.8497979;
Console.WriteLine(string.Format(new DoubleFormatter(), "w={0} h={1}", width, height));

Output:

w=15.776 h=12.850

So now we have a reusable format for doubles – 3 decimal places with dot separator. That is nice, but this formatter is very simple – it formats everything (eg. DateTime) as „0:000“. This is a fast version if you know that you will only use it for formatting lots of doubles.

The real version should look like this:

[C#]

public class DoubleFormatter : IFormatProvider, ICustomFormatter
{
// always use dot separator for doubles
private CultureInfo enUsCulture = CultureInfo.GetCultureInfo("en-US");
 
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg is double)
{
if (string.IsNullOrEmpty(format))
{
// by default, format doubles to 3 decimal places
return string.Format(enUsCulture, "{0:0.000}", arg);
}
else
{
// if user supplied own format use it
return ((double)arg).ToString(format, enUsCulture);
}
}
// format everything else normally
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, formatProvider);
else
return arg.ToString();
}
 
public object GetFormat(Type formatType)
{
return (formatType == typeof(ICustomFormatter)) ? this : null;
}
}

Example:

[C#]

Console.WriteLine(string.Format(new DoubleFormatter(),
"Numbers {0} and {1:0.0}. Now a string {2}, a number {3}, date {4} and object: {5}",
1.234567, -0.57123456, "Hi!", 5, DateTime.Now, new object()));

Output:

Numbers 1.235 and -0.6. Now a string Hi!, a number 5, date 12.6.2009 17:11:35
and object: System.Object

Other examples with custom formatters can be found in MSDN. See example with formatter for 12-digit account numbers (12345–678–9012) or example with binary, octal, and hexadecimal formatter.

IFormatProvider for Numbers [C#]

http://www.csharp-examples.net/iformatprovider-numbers/

This example shows how to convert float to string and string to float using IFormatProvider. To get IFormatProvider you need to get CultureInfo instance first.

Get invariant or specific CultureInfo

Invariant culture is a special type of culture which is culture-insensitive. You should use this culture when you need culture-independent results, e.g. when you format or parse values in XML file. The invariant culture is internally associated with the English language. To get invariantCultureInfo instance use static property CultureInfo.In­variantCulture.

To get specific CultureInfo instance use static method CultureInfo.Get­CultureInfo with the specific culture name, e.g. for the German language CultureInfo.GetCultureInfo("de-DE").

Format and parse numbers using the IFormatProvider

Once you have the CultureInfo instance use property CultureInfo.Num­berFormat to get anIFormatProvider for numbers (the NumberFormatInfo object)

[C#]

// format float to string
float num = 1.5f;
string str = num.ToString(CultureInfo.InvariantCulture.NumberFormat); // "1.5"
string str = num.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat); // "1,5"

[C#]

// parse float from string
float num = float.Parse("1.5", CultureInfo.InvariantCulture.NumberFormat);
float num = float.Parse("1,5", CultureInfo.GetCultureInfo("de-DE").NumberFormat);
时间: 2024-10-08 18:04:29

Custom IFormatProvider的相关文章

C#详解format函数,各种格式化

一.String Format for Double Digits after decimal point This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will b

自定义元素(custom elements)

记录下自定义html自定义元素的相关心得: 浏览器将自定义元素保留在 DOM 之中,但不会任何语义.除此之外,自定义元素与标准元素都一致 事实上,浏览器提供了一个HTMLUnknownElement,HTMLElement对象,所有自定义元素都是该对象的实例. var tabs=document.createElement("tabs"); console.log(tabs instanceof HTMLUnknownElement);//true console.log(tabs i

SharePoint 2010/SharePoint 2013 Custom Action: 基于Site Collection 滚动文字的通知.

应用场景: 有时候我们的站点需要在每个页面实现滚动文字的通知,怎么在不修改Master Page的情况下实现这个功能?我们可以使用Javascript 和 Custom Action 来实现. 创建一个Custom Action.主要使用到 Location = 'ScriptLink' 属性, 该属性可以动态的加载JavaScript 文件链接和代码块到模板页.代码如下: <Elements xmlns="http://schemas.microsoft.com/sharepoint/&

redmine computed custom field formula tips

项目中要用到Computed custom field插件,公式不知道怎么写,查了些资料,记录在这里. 1.http://apidock.com/ruby/Time/strftime 查看ruby的字符串格式,用于改写Date/time format只显示日期,不显示时间. 2.https://github.com/annikoff/redmine_plugin_computed_custom_field/issues/34 看到formula里可以写复杂代码,比如增加变量.指定返回值等. 3.

Spring Custom Bean with BeanPostProcessor

Spring Custom Bean 1.BeanPostProcessors 这个接口是在spring容器初始化完bean之后 才会被调用,这个接口针对是一个容器,不能夸容器操作的,这个只能在初始化bean之后再改变一些自己的内容,如果想改变bean的结构,需要另外的一个接口:BeanFactoryPostProcessor

Cookies and Custom Protocols

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/CookiesandCustomProtocols/CookiesandCustomProtocols.html#//apple_ref/doc/uid/10000165i-CH10-SW3 If your app needs to manage cookies programmatically, such as

Angular2 - Starter - Pipes, Custom Pipes

在Angular2 模板中,我们在显示数据时,可以使用通道将数据转换成相应的格式的值的形式来显示,而且这不改变源数据.比如,我们可以使用date通道来转换时间显示的格式: {{date | date:'yyyy-MM-dd'}} ,(1) 以下是Angular提供的基本的通道. Basic Pipes Pipe Name Usage Parameters or Effection currency {{test.currency | currency }} 1234569678 > USD1,2

Unity Editor Extensions – Custom Inspectors

?? 转载请注明出处:http://blog.csdn.net/u010019717 更全的内容请看我的游戏蛮牛地址:http://www.unitymanual.com/space-uid-18602.html 这是在"Unity Editor Extension"系列的第 2 次帖子. post描述了为创建自定义inspectors面板在 Unity 编辑器的基本步骤.在该系列的下一个posts,我将深入探讨更高级的主题,例如inspectors及Unity's serializa

Writing a Reusable Custom Control in WPF

In my previous post, I have already defined how you can inherit from an existing control and define your own reusable chunk. The reusable XAML code that I have defined there is actually a composition of one of more existing elements in a common desig