So che questo è un filo vecchio, ma io Ho appena dovuto farlo. Mentre gli altri approcci qui funzionano, volevo un modo semplice per essere in grado di influenzare molte chiamate a string.format
. Quindi aggiungere lo Math.Truncate
a tutte le chiamate non era una buona opzione. Inoltre, poiché parte della formattazione è memorizzata in un database, lo ha reso ancora peggiore.
Così, ho fatto un provider personalizzato formato che mi permettesse di aggiungere troncamento per la stringa di formattazione, ad esempio:
string.format(new FormatProvider(), "{0:T}", 1.1299); // 1.12
string.format(new FormatProvider(), "{0:T(3)", 1.12399); // 1.123
string.format(new FormatProvider(), "{0:T(1)0,000.0", 1000.9999); // 1,000.9
L'implementazione è piuttosto semplice ed è facilmente estensibile ad altri requisiti.
public class FormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof (ICustomFormatter))
{
return this;
}
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg == null || arg.GetType() != typeof (double))
{
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
}
}
if (format.StartsWith("T"))
{
int dp = 2;
int idx = 1;
if (format.Length > 1)
{
if (format[1] == '(')
{
int closeIdx = format.IndexOf(')');
if (closeIdx > 0)
{
if (int.TryParse(format.Substring(2, closeIdx - 2), out dp))
{
idx = closeIdx + 1;
}
}
else
{
throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
}
}
}
double mult = Math.Pow(10, dp);
arg = Math.Truncate((double)arg * mult)/mult;
format = format.Substring(idx);
}
try
{
return HandleOtherFormats(format, arg);
}
catch (FormatException e)
{
throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
}
}
private string HandleOtherFormats(string format, object arg)
{
if (arg is IFormattable)
{
return ((IFormattable) arg).ToString(format, CultureInfo.CurrentCulture);
}
return arg != null ? arg.ToString() : String.Empty;
}
}
Che cosa si intende per " sensibile alla cultura "? Ciò significa che l'esito della formattazione deve variare in base al valore culturale fornito dal programmatore? O vuoi usare qualunque cultura è l'impostazione predefinita per il thread corrente? – CesarGon