Format a double to two digits after the comma without rounding up or down
c#, decimal, formatting, rounding
Solution
Have you tried
Math.Round(0.33333333333, 2);
Update*
If you don't want the decimal rounded another thing you can do is change the double to a string and then get get a substring to two decimal places and convert it back to a double.
doubleString = double.toString();
if(doubleString.IndexOf(',') > -1)
{
doubleString = doubleString.Substring(0,doubleString.IndexOf(',')+3);
}
double = Convert.ToDouble(doubleString);
You can use a if statement to check for .99 and change it to 1 for that case.
Problem
I have been searching forever and I simply cannot find the answer, none of them will work properly. I want to turn a double like 0.33333333333 into 0,33 or 0.6666666666 into 0,66 Number like 0.9999999999 should become 1 though. I tried various methods like ``` value.ToString("##.##", System.Globalization.CultureInfo.InvariantCulture) ``` It just returns garbage or rounds the number wrongly. Any help please? Basically every number is divided by 9, then it needs to be displayed with 2 decimal places without any rounding. I have found a nice function that seems to work well with numbers up to 9.999999999 Beyond that it starts to lose one decimal number. With a number like 200.33333333333 its going to just display 200 instead of 200,33. Any fix for that guys? Here it is: ``` string Truncate(double value, int precision) { string result = value.ToString(); int dot = result.IndexOf(','); if (dot < 0) { return result; } int newLength = dot + precision + 1; if (newLength == dot + 1) { newLength--; } if (newLength > result.Length) { newLength = result.Length; } return result.Substring(0, newLength); } ```