c# - Format number to string with custom group and decimal separator without changing precision -
i format numbers strings in c# custom group/thousands separator , decimal separator. group , decimal separator can change based on user input use numberformatinfo object instead of hardcoded formatting string. code below gets proper separators, changes precision of number 2 decimal places, whereas want keep full precision of number , show decimal places when needed (so integer values dont have decimal places).
how can achieve this? guessing need change "n" parameter, change what?
double n1 = 1234; double n2 = 1234.5; double n3 = 1234567.89; double n4 = 1234.567; var nfi = new numberformatinfo(); nfi.numberdecimalseparator = ","; nfi.numbergroupseparator = " "; string s1 = n1.tostring("n", nfi); //want "1 234" "1 234,00" string s2 = n2.tostring("n", nfi); //want "1 234,5" "1 234,50" string s3 = n3.tostring("n", nfi); //correct output of "1 234 567,89" string s4 = n4.tostring("n", nfi); //want " 1 234,567" "1 234,57"
below solution came extension method.
public static string format(this double d, numberformatinfo numberformatinfo) { string s = d.tostring(cultureinfo.invariantculture); int index = s.indexof('.'); int decimalplaces = index == -1 ? 0 : s.length - index - 1; return d.tostring($"n{decimalplaces}", numberformatinfo); }
Comments
Post a Comment