skip to Main Content

I have this rounding where I am trying to round the decimal price so that the decimals always round to either .00 or .05 (using this rule .00,.01,.02,.03,.04 = .00 and .05,.06,.07,.08,.09 = .05) – but right now with the below code it also returns .01, .02 etc in the decimal numbers.

 // 2 is the number of decimals that it should return.
 decimal unitPriceFloored = System.Math.Round(price, 2, System.MidpointRounding.ToZero);

How can I change it so that it round the price to .00 or .05 in the decimals?
Just to clarify – this should work the same way with .10 and .15 etc. (all 2 decimal comma numbers)

2

Answers


  1. I don’t know of a built-in function to do this. Here’s a way:

    for(decimal m = 1m; m < 1.2m; m = m + 0.01m)
       WriteLine( $"{m} -> {Math.Truncate(m) + (int)(((m - Math.Truncate(m))*100)/5) * 0.05m }");
    

    This prints:

    1 -> 1.00 
    1.01 -> 1.00
    1.02 -> 1.00
    1.03 -> 1.00
    1.04 -> 1.00
    1.05 -> 1.05
    1.06 -> 1.05
    1.07 -> 1.05
    1.08 -> 1.05
    1.09 -> 1.05
    1.10 -> 1.10
    1.11 -> 1.10
    1.12 -> 1.10
    1.13 -> 1.10
    1.14 -> 1.10
    1.15 -> 1.15
    1.16 -> 1.15
    1.17 -> 1.15
    1.18 -> 1.15
    1.19 -> 1.15
    
    Login or Signup to reply.
  2. This should work:

    decimal  cal   ( decimal d )
    {
    
     decimal num =  d;
    
    decimal or =  digits(  num); 
     
    if (or >= .05m)  return (num - or) + .05m ; 
     return   num -or;
    }
    
    
    
    
     decimal  digits   (   decimal  x )
    { while( x >  1000 )
    {
        x-=1000; 
    }
    while ( x >100)
    {
         x-=100; 
    }
    while(x > 10)
    {
        x -= 10; 
    }
      while (   x   >= 1   )
    {
        x--; 
    }
    
    return subdigits (x) ; 
    }    
    decimal subdigits( decimal some)
    {
    
    
    while ( some  >=  0.1m )
    {
         some   -=.1m ;
    }
    
    return  some ;
    
    }
    

    PS: Still have to get used to stackoverflow formatting,sorry …
    Results are the following:
    1->1
    1.01->1.0
    1.02->1
    1.03->1
    1.04->1

    1.05->1.05
    1.06->1.05
    1.07->1.05
    1.08->1.05
    1.09->1.05
    1.1-<1.1
    2->2
    Now it should work 😀

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search