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. Yii源码阅读笔记(十一)

    controller类的render部分,用于渲染视图和布局文件: /** * Returns all ancestor modules of this controller. * 获取当前控制器所有 ...

  2. PHP关闭提示、打印配置

    打印配置 PHP.exe -i > Info.txt 关闭 PHP 提示的方法 搜索php.ini: error_reporting = E_ALL 改为: error_reporting = ...

  3. 医生加号页改版,就一个Bug, 看医生工作台一期需求

    8/8日报 分级埋点:     [MobClick event:UmengPagePlusDoctor attributes:@{@"page":@"plusPage&q ...

  4. php数据缓存

    用php进行微信开发时,碰到access_token长久保存的问题,以前都是用框架里的Cache直接set.get一下就完了.现在没框架可用了,只好自己动手写一个cache暂时用. 这个Cache类用 ...

  5. IOS常见的三种回调方法介绍

    认识下三种IOS常见的回调模式. 代理模式作为IOS中最常见的通讯模式,代理几乎无处不在. 这里有一个数组,我们首先通过代理的方式将数组传递到其他方法中去. 设置协议及方法 @protocol Cal ...

  6. HBase学习笔记-基础(一)

    HBase版本:0.97 1.Get Gets实在Scan的基础上实现的. 2.联合查询(Join) HBase是否支持联合是一个网上常问问题.简单来说 : 不支持.至少不像传统RDBMS那样支持. ...

  7. 另一个SqlParameterCollection中已包含SqlParameter

    一般情况下,我们定义的一个SqlParameter参数数组,如: SqlParameter[] parms =             {                new SqlParamete ...

  8. 使用shell测试cdn状态

    公司使用多家cdn,测试cdn在各个地方的响应情况,以便于提高视频访问的用户体验.分别在阿里云华南1,华东1,华东2,华北2等不同地区节点测试.该随笔为自己所用.   1.该脚本会测试某一cdn的ur ...

  9. Android Error:warning: Ignoring InnerClasses attribute for an anonymous inner class

    今天项目发布时遇到了这个问题,在低版本设备上面死活发布不上去,还有打包也打不成功,折腾了好长一段时间,网上大部分给出的 解决方案都是说 在工程的混淆配置文件 proguard-rules.pro 中加 ...

  10. Android 退出app,后台推送的服务也停止了,怎么可以做到不停止后台服务呢?

    service粘性等的那4种方式试了,三星的可以,小米老款手机可以,新款不行,华为新款也不行,还有魅族什么的,都不行,新款的手机上都有一个安全中心,只有在安全中心里面添加上允许app自启动才可以 怎么 ...