Custom IFormatProvider
The following example shows how to write a custom IFormatProvider which you can use in methodString.Format(IFormatProvider, …).
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.InvariantCulture.
To get specific CultureInfo instance use static method CultureInfo.GetCultureInfo 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.NumberFormat 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的更多相关文章
- C#详解format函数,各种格式化
一.String Format for Double Digits after decimal point This example formats double to string with fix ...
- 使用DateTime的ParseExact方法实现特殊日期时间的方法详解(转)
本篇文章是对使用DateTime的ParseExact方法实现特殊日期时间的方法进行了详细的分析介绍,需要的朋友参考下 今天遇到一个特别的需求,需要从下面的字符串中转换成一个DateTime对象: [ ...
- 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 ...
- Spring Enable annotation – writing a custom Enable annotation
原文地址:https://www.javacodegeeks.com/2015/04/spring-enable-annotation-writing-a-custom-enable-annotati ...
- SharePoint2013 Set a custom application page as site welcome page
本文主要介绍如何添加一个custom application page as site welcome page 1.首先创建一个sharepoint 2013 empty solution, add ...
- WebComponent魔法堂:深究Custom Element 之 从过去看现在
前言 说起Custom Element那必然会想起那个相似而又以失败告终的HTML Component.HTML Component是在IE5开始引入的新技术,用于对原生元素作功能"增强& ...
- WebComponent魔法堂:深究Custom Element 之 标准构建
前言 通过<WebComponent魔法堂:深究Custom Element 之 面向痛点编程>,我们明白到其实Custom Element并不是什么新东西,我们甚至可以在IE5.5上定 ...
- WebComponent魔法堂:深究Custom Element 之 面向痛点编程
前言 最近加入到新项目组负责前端技术预研和选型,一直偏向于以Polymer为代表的WebComponent技术线,于是查阅各类资料想说服老大向这方面靠,最后得到的结果是:"资料99%是英语 ...
- [转]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 ...
随机推荐
- Unity 中 使用c#线程
使用条件 天下没有免费的午餐,在我使用unity的那一刻,我就感觉到不自在,因为开源所以不知道底层实现,如果只是简单的做点简单游戏,那就无所谓的了,但真正用到实际地方的时候,就会发现一个挨着一个坑 ...
- Dom4j
Dom4j http://baike.baidu.com/link?url=2XOnr06saKUd-9By1GyPxIolXMQhf_C-CnMFll_yhtR4m00i27zphbkI5-dGpw ...
- mysql import data slow solution---overview information
1 SELECT SUM(DATA_LENGTH)+SUM(INDEX_LENGTH) FROM information_schema.tables WHERE TABLE_SCHEMA='dat ...
- ManualResetEvent和AutoResetEvent的区别实例
ManualResetEvent和AutoResetEvent的作用可以理解为在线程执行中插入停顿点flag终止程序运行,然后通过设置flag的状态来使得程序继续运行. 两者的区别是:ManualRe ...
- php练习:每5个商品一排
老板说: 我要一行5个商品,每个长得都不一样 <!DOCTYPE html> <html lang="en"> <head> <meta ...
- windows下安装和配置mongoDB
上次在mac下安装和配置了mongodb,这次在windows下也尝试安装和配置mongodb. 1.首先下载mongodb压缩包,下载后解压到D盘或E盘.如下: 2.配置环境变量:桌面—计算机右键— ...
- [LeetCode] Letter Combinations of a Phone Number(bfs)
Given a digit string, return all possible letter combinations that the number could represent. A map ...
- Sql Server中通配符
Sql Server中通配符的使用 通配符_ "_"号表示任意单个字符,该符号只能匹配一个字符."_"可以放在查询条件的任意位置,且只能代表一个字符.一个汉字只 ...
- java发展道路
1.
- MSP430之ADC采集滤波
占位符 /* 加权平均滤波 */ ] = {,,,,,,,,,,,,}; ++++++++++++; unsigned ; ; i<ADCN; i++) { temp += arr[i]*coe ...