From 100.11 to 100.15 and from 100.16 to 100.20 in C #

From 100.11 to 100.15 and from 100.16 to 100.20 in C #

I tried all of this, but none of this helps me.

Math.Round(100.11, 2,MidpointRounding.AwayFromZero); //gives 100.11 Math.Round(100.11, 2,MidpointRounding.ToEven);//gives 100.11 Math.Round((Decimal)100.11, 2)//gives 100.11 (100.11).ToString("N2"); //gives "100.11" Math.Floor(100.11);// gives 100.0 (100.11).ToString("#.##");//gives "100.11" Math.Truncate(100.11);// gives 100.0 Math.Ceiling(100.11);//gives 101.0 (100.11).ToString("F4");// gives "100.1100" 
+6
source share
3 answers

The issue requires samples poorly; if rounding is expected with a delta of 1/20 , that is:

  100.10 -> 100.10 100.11 -> 100.15 // <- round UP; that why 100.15 not 100.10 ... 100.15 -> 100.15 100.16 -> 100.20 ... 100.20 -> 100.20 100.21 -> 100.25 

you can use this simple code

  Double value = 100.11; Double result = Math.Round(value * 20.0 + 0.49999999) / 20.0; 
+4
source

This should give the desired result.

 decimal Round (decimal value, decimal granularity) { return Math.Ceiling(value/granularity+0.5M)*granularity; } // myResult = Round(110.11,0.05); // myResult = Round(110.16,0.05); 

In general: set the granularity to the decimal value of how you want to round the values, for example. 0.1 rounded to the nearest decimal place. You can also apply odd values ​​such as 0.25 , which will be rounded to 0.25 , 0.50 , 0.75 and 1.0 .

A +0.5M will be rounded to the nearest value (instead of rounding).

+8
source

The answer proposed by Alzaymar is very interesting and useful. But note that this is NOT entirely useful when working with float or double.

In general, you can use a similar approach to purely "granulate" floating point values:

 public double Granularize(double value, double granularity) { var precision = (Decimal.GetBits((decimal)value)[3] >> 16) & 0x000000FF; return Math.Round(Math.Round(value / granularity, 0) * granularity, precision); } 

Obviously, you can get ceiling methods for float / double using the same basic premise.

I just wanted to point out that using granularity, such as 0.1d, will NOT give a properly granular result without rounding to the finest detail. Sometimes you will receive a false inaccuracy somewhere around the 13th decimal place.

0
source

All Articles