Link to home
Create AccountLog in
Avatar of letharion
letharionFlag for Sweden

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.8554154707894045251247690

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.
Avatar of kiruba_karan_d
kiruba_karan_d
Flag of India image

Hi

//Round (Number, NumDigitsAfterDecimal)
System.Math.Round(22.3433, ); //22.3
Hello letharion,

Math.Round(Number,Precision);

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.AwayFromZero) = 5557.9

 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
Avatar of letharion

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.
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
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
ASKER CERTIFIED SOLUTION
Avatar of TimCottee
TimCottee
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Thank you very much. Works wonders :)