I'm looking to String.Format or ToString() a decimal to get just the fraction part.
'123.56m => "56"
C# decimal format to display just the fraction part
579 views Asked by Grudzinski At
2
There are 2 answers
1
On
Another approach assuming you have up to 2 digits fraction
decimal value = 123.56m;
string result = (value % 1 * 100).ToString("F0"); //"56"
string Split() approach
decimal value = 123.56m;
char separator = NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator.First();
string result = value.ToString("F2").Split(separator ).Last();
.Substringcall too.CultureInfo.InvariantCulture, otherwise per-user language/culture/region settings will mean possibly different default formatting and radix-point (decimal-point) chars will be used, but usingCultureInfo.InvariantCulturemeans the radix-point will always be an ASCII dot'.'char.IFormatProviderandICustomFormatter, unfortunatelyDecimal.ToString(IFormatProvider)requiresprovider.GetFormat to return aNumberFormatInfovalue and doesn't support usingICustomFormatter.IFormatProviderandICustomFormatterwill work if used withString.Format, but that's not in your question.Math.Abs()to convert negative numbers to positive numbers (otherwise there's a leading-sign char which would complicate the.Substringcall-site).".############################"as the format-string corresponds to the maximum number of decimal places in aDecimalvalue (i.e. 28 digits)..part is necessary.fractionalPartis0then there are no digits to render and.ToString( format: "#.########", provider: CultureInfo.InvariantCulture )will return""(which will cause.Substring( startIndex: 1 )to throw an exception, so we can skip that with a ternary expression).You can simplify it down to 2 lines:
Examples: