Posts

Showing posts with the label rounding

Round a decimal to the first decimal position that is not zero

I want to shorten a number to the first significant digit that is not 0. The digits behind should be rounded. Examples: 0.001 -> 0.001 0.00367 -> 0.004 0.00337 -> 0.003 0.000000564 -> 0.0000006 0.00000432907543029 -> 0.000004 Currently I have the following procedure: if (value < (decimal) 0.01) { value = Math.Round(value, 4); } Note: numbers will always be positive the number of significant digits will always be 1 values larger 0.01 will always be rounded to two decimal places, hence the if < 0.01 As you can see from the examples above, a rounding to 4 Decimal places might not be enough and the value might vary greatly. I would declare precision variable and use a loop iteration multiplies that variable by 10 with the original value it didn't hit, that precision will add 1. then use precision variable be Math.Round second parameter. static decimal RoundFirstSignificantDigit(decimal input) { int precision = 0; var val = input; while (Math.A...

How to round to nearest even integer?

My last goal is always to round to the nearest even integer. For example, the number 1122.5196 I want as result 1122. I have tried this options: Math.Round(1122.5196d, 0, MidpointRounding.ToEven); // result 1123 Math.Round(1122.5196d, 0, MidpointRounding.AwayFromZero); // result 1123 At the end, what I would like to get it is always the nearest even intenger. For example: 1122.51 --> 1122 1122.9 --> 1122 (because the nearest int is 1123 but it is odd, and 1122 is nearer than 1124) 1123.0 --> 1124 (the next even value, the next higher even value) I only work with positive numbers. And so on. There are some method that do that or I should to implement my own method? Try this (let's use Math.Round with MidpointRounding.AwayFromZero in order to obtain "next even value" but scaled - 2 factor): double source = 1123.0; // 1124.0 double result = Math.Round(source / 2, MidpointRounding.AwayFromZero) * 2; Demo: double[] tests = new double[] { 1.0, 1123...