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);

Custom IFormatProvider的更多相关文章

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

    一.String Format for Double Digits after decimal point This example formats double to string with fix ...

  2. 使用DateTime的ParseExact方法实现特殊日期时间的方法详解(转)

    本篇文章是对使用DateTime的ParseExact方法实现特殊日期时间的方法进行了详细的分析介绍,需要的朋友参考下 今天遇到一个特别的需求,需要从下面的字符串中转换成一个DateTime对象: [ ...

  3. AutoMapper:Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type

    异常处理汇总-后端系列 http://www.cnblogs.com/dunitian/p/4523006.html 应用场景:ViewModel==>Mode映射的时候出错 AutoMappe ...

  4. Spring Enable annotation – writing a custom Enable annotation

    原文地址:https://www.javacodegeeks.com/2015/04/spring-enable-annotation-writing-a-custom-enable-annotati ...

  5. SharePoint2013 Set a custom application page as site welcome page

    本文主要介绍如何添加一个custom application page as site welcome page 1.首先创建一个sharepoint 2013 empty solution, add ...

  6. WebComponent魔法堂:深究Custom Element 之 从过去看现在

    前言  说起Custom Element那必然会想起那个相似而又以失败告终的HTML Component.HTML Component是在IE5开始引入的新技术,用于对原生元素作功能"增强& ...

  7. WebComponent魔法堂:深究Custom Element 之 标准构建

    前言  通过<WebComponent魔法堂:深究Custom Element 之 面向痛点编程>,我们明白到其实Custom Element并不是什么新东西,我们甚至可以在IE5.5上定 ...

  8. WebComponent魔法堂:深究Custom Element 之 面向痛点编程

    前言  最近加入到新项目组负责前端技术预研和选型,一直偏向于以Polymer为代表的WebComponent技术线,于是查阅各类资料想说服老大向这方面靠,最后得到的结果是:"资料99%是英语 ...

  9. [转]Writing Custom Middleware in ASP.NET Core 1.0

    本文转自:https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/ One of the new ...

随机推荐

  1. 字符数组char

     数组做sizeof的参数不退化,传递给strlen就退化为指针: #include<stdio.h> #include<stdlib.h> #include<strin ...

  2. PHP date 格式化一个本地时间/日期

    PHP date 格式化一个本地时间/日期 date (PHP 4, PHP 5) date — 格式化一个本地时间/日期 说明 string date ( string $format [, int ...

  3. shell 中的引用

    1. 什么叫引用对 shell 脚本.程序.终端命令.变量.字符串等结果的反馈.2. 引用的类型 " " 双引号           ` 反引号' ' 单引号           ...

  4. php--某个字符在字符串中的位置比较

    <?php $haystack = 'helloe'; $needle = 'e'; $pos = stripos($haystack, $needle); echo "\n" ...

  5. 11.PHP内核探索:嵌入式PHP PHP内核探索:嵌入式PHP

    从PHP源码目录结构的介绍以及PHP生命周期可知:嵌入式PHP类似CLI,也是SAPI接口的另一种实现. 一般情况下,它的一个请求的生命周期也会和其它的SAPI一样:模块初始化=>请求初始化=& ...

  6. space ship

    按下向上箭头,飞船速度不是一直增加 而且飞船移动的方向是固定的不是有角度的 按下箭头飞船可以飞了,但是不减速 加一个keyup handler就可以啦!可以一直加速,不按的时候也可以减速 按下向下按钮 ...

  7. Java单链表的实现

    将结点Node进行封装,假设Node的操作有增加,删除,查找,打印几个操作.将Node实现为链表Link的内部类,简化代码. package Chapter5; import java.securit ...

  8. JS中基本window对象操作

    ---恢复内容开始--- 一.使用window中的属性时   window.属性,直接跟属性名.而调用window的函数时  window.hanshu(): 要在其函数名后面加括号. 二.windo ...

  9. struts1 plugin

    struts plugin 在struts.xml中注册之后,在系统启动之后调用 init 方法,通常在init方法中进行转化器的注册,在destory中移除转化器 1. struts文件 <p ...

  10. 使用NSTimer过程中最大的两个坑

    坑1. retain cycle问题. 在一个对象中使用循环执行的nstimer时,若希望在对象的dealloc方法中释放这个nstimer,结局会让你很失望. 这个timer会导致你的对象根本不会被 ...