In C# I want a function that rounds a given double to a given amount of decimals. I always want my function to return a value (which can be a string) with the given amount of decimals. If necessary, trailing zeros need to be added.
Example:
string result = MyRoundingFunction(1.01234567, 3);
// this must return "1.012"
That's easy, it's just rounding and converting to string. But here comes the problem:
string result2 = MyRoundingFuntion(1.01, 3);
// this must return "1.010"
Is there a convenient/standard way to do this, or do I manually need to add trailing zeros?
Any help is appreciated. Note that in the real life application I can't hard code the number of decimals.
You should first round, then format.
String.Format("{0:0.000}", Math.Round(someValue, 2));
What you should read is:
Math.Round
String.Format, Custom Numeric Format
As option you could use the extension to support that
Extension Methods
You can create a formatter like this example:
int numDigitsAfterPoint = 5;
double num = 1.25d;
string result = num.ToString("0." + new string('0', numDigitsAfterPoint));
or (more easily)
string result = num.ToString("F" + numDigitsAfterPoint);
As a sidenote, ToString
uses the MidpointRounding.AwayFromZero
instead of the MidpointRounding.ToEven
(also called Banker's Rounding). As an example:
var x1 = 1.25.ToString("F1");
var x2 = 1.35.ToString("F1");
var x3 = Math.Round(1.25, 1).ToString();
var x4 = Math.Round(1.35, 1).ToString();
These will produce different result (because Math.Round
normally uses MidpointRounding.ToEven
)
And note that internally ToString()
seems to do some "magic" before rounding digits. For doubles, if you ask him less than 15 digits, I think it rounds to 15 digits first and then rounds to the right number of digits. See here https://ideone.com/ZBEis9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With