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 ...
随机推荐
- PHP学习(五)----jQuery和JSON数据
对于jQuery: jQuery 是一个 JavaScript 库. jQuery 极大地简化了 JavaScript 编程.
- Java管道流
管道流的主要作用可以用于两个线程之间的通信,有管道输出流 PipeOutputStream和管道输入流 PipeInputStream.然后通过connect将两个管道连接起来. import jav ...
- Delphi指针及其它(转)
一.指针:指向一个内存地址的变量或参数. 二.定义指针的方式如下: P: Pointer; //定义了可以指向任何类型的指针,Pointer 为无类型指针: Q, R: ^TType; //定义了指向 ...
- C++ 栈和队列
使用标准库的栈和队列时,先包含相关的头文件 #include<stack> #include<queue> 定义栈如下: stack<int> stk; 定义队列如 ...
- unity3d中控制物体移动方法有那些及区别
1. 利用GameObject的Translate,直接改变它的Transform,前提是需要你实现准备变换矩阵.2. 用MoveTo方法,你只要知道你的目标位置即可.3. 用Math的Lerp方法计 ...
- log4j常用配置以及日志文件保存位置
log4j.rootLogger=INFO,CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender ...
- Oracle存储过程java 调用
1.nest表组合成结果集,然后以游标变量的形式返回 --创建类型 create or replace package mytest is -- Author : ADMINISTRATOR -- ...
- Java Blocking Queue
//Listing 8-1. The Blocking Queue Equivalent of Chapter 3’s PC Application import java.util.concurre ...
- error: jump to label ‘XXXX’ [-fpermissive]
http://www.cnblogs.com/foohack/p/4090124.html 下面的类似的源码在MSVC上能正确编译通过.但是gcc/g++上就会错: 1. if(expr)2. got ...
- 创建QT CREATOR对话框报错 linux QT Creator :-1: error: cannot find -lGL
装完QT5.4 及 QT Creator3.3 后 创建第一个QT Widgets Application(相当于窗体) 应用程序 报如上错误. 执行 sudo apt-get install lib ...