Skip to content

Instantly share code, notes, and snippets.

@yuessir
Created October 2, 2018 08:17
Show Gist options
  • Save yuessir/4efc67ad80b0809ab1707bc7ce20913e to your computer and use it in GitHub Desktop.
Save yuessir/4efc67ad80b0809ab1707bc7ce20913e to your computer and use it in GitHub Desktop.
Chop Decimals (NO Rounding) C#
#Implementing IFormatProvider, ICustomFormatter
forking from https://stackoverflow.com/a/28342440/4246719
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.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.InvariantCulture);
}
return arg != null ? arg.ToString() : String.Empty;
}
}
usage:
var str1 = string.Format(new FormatProvider(), "{0:T(3)##.##}", 1.12999); // 1.13
var str2 = string.Format(new FormatProvider(), "{0:T(3)}", 1.12399); // 1.123
var str3 = string.Format(new FormatProvider(), "{0:T(1)0,000.0}", 1000.9999); // 1,000.9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment