letharion
asked on
Writing a function to round to "arbitrary" precision in C#
I wish create a function (or use one if it already exists) that can round to any precision.
I have calculation that returns a value, often with a lot of decimals.
Say I have
5557.855415470789404525124 7690
And sometimes I wanna round it to the nearest whole number. => 5558
Sometimes to nearest .1 => 5557.9
Or to .00001 => 5557.85542
And so on.
I have calculation that returns a value, often with a lot of decimals.
Say I have
5557.855415470789404525124
And sometimes I wanna round it to the nearest whole number. => 5558
Sometimes to nearest .1 => 5557.9
Or to .00001 => 5557.85542
And so on.
Hello letharion,
Math.Round(Number,Precisio n);
At its most basic, there are a number of options available with this that also allow you control over how midpoint rounding is carried out etc.
Regards,
TimCottee
Math.Round(Number,Precisio
At its most basic, there are a number of options available with this that also allow you control over how midpoint rounding is carried out etc.
Regards,
TimCottee
Hi
Math.Round(5557.8, 1, MidpointRounding.AwayFromZ ero) = 5557.9
Math.Round(5557.8, 1, MidpointRounding.ToEven) = 5557.8
Math.Round(5557.8, 1, MidpointRounding.AwayFromZ
Math.Round(5557.8, 1, MidpointRounding.ToEven) = 5557.8
kiruba_karan_d,
Actually not quite, 5557.8 will always be rounded to 5557.8 with 1 decimal place.
5557.85 would be rounded to 5557.9 and 5557.8 respectively using those methods.
TimCottee
Actually not quite, 5557.8 will always be rounded to 5557.8 with 1 decimal place.
5557.85 would be rounded to 5557.9 and 5557.8 respectively using those methods.
TimCottee
ASKER
I realise I wasn't really clear. Your solutions are great, but I might also want to round to the nearest .25 or the nearest 1/32 (0.03125)
That's where things get complicated. I should've taken such examples in my original post.
That's where things get complicated. I should've taken such examples in my original post.
letharion,
That is a little trickier but then you have to apply the old methods. Multiply by your factor, apply rounding and then divide by your factor to get the result.
TimCottee
That is a little trickier but then you have to apply the old methods. Multiply by your factor, apply rounding and then divide by your factor to get the result.
TimCottee
ASKER
TimCottee: I'm sorry, but I don't understand. The way I read your post:
Desired result 5557.8554 rounded to .25 => 5557.75
5557.8554 * 25 = 138946.385 =>
138946 / 25 = 5557.84
Desired result 5557.8554 rounded to .25 => 5557.75
5557.8554 * 25 = 138946.385 =>
138946 / 25 = 5557.84
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Thank you very much. Works wonders :)
//Round (Number, NumDigitsAfterDecimal)
System.Math.Round(22.3433,