Round to 25, 50, 75, 100

后端 未结 5 1947
说谎
说谎 2021-01-28 03:49

I\'m not a Math person so I\'m having a hard time to come up with a calculation to round the decimals to 25, 50, 75 and 100. And this will not be the typical round off because t

相关标签:
5条回答
  • 2021-01-28 03:56

    I suggest using types without floating point.

    decimal RoundNearestCents(decimal price) {
        // no problems with floating point as all calculations are exact
        return Math.Floor((price * 100 + 24) / 25) * 25 / 100;
    }
    

    -- Why is your price string?

    -- Because it's coming from a textbox.

    I assume your textbox should support limiting your input to decimal numbers with at most 2 decimal places. So its value will be decimal already. However I don't know what is your application type. If you still want to accept string then consider using decimal.TryParse method to convert it to decimal.

    0 讨论(0)
  • 2021-01-28 04:05
    public float RoundNearestCents(double d)
    {
      return (double)(Math.Ceiling(d * 4)) / 4;
    }
    
    0 讨论(0)
  • 2021-01-28 04:12

    My code may not be the best out there, but it will work. In your function create a float and an int like so.

    public float RoundNearestCents(String price)
    {
        float srp = float.Parse(price);
        int srp1 = Int32.Parse(price);
        if((srp-srp1)>=0.5) 
            srp1++;
        else 
            return srp1;
        return srp1;
    }
    

    The int would truncate out the decimal part, which is like flooring the price.

    0 讨论(0)
  • 2021-01-28 04:15

    I would use something like this:

    float RoundNearestCents(float price)
        {
        price*=(100/25.0); // now fractions are going away
        if (price-floor(price)>=0.5) price++; // round up if fraction above 0.5
        return floor(price)*(25.0/100.0); // cut of the fraction and restore original range
        }
    
    0 讨论(0)
  • 2021-01-28 04:17

    This is one way:

    public decimal RoundNearestCents(decimal price)
    {
        decimal srp = price * 100;
        decimal m = srp % 25;
        srp = srp - m + (m > 0 ? 25 : 0);
        return srp / 100;
    }
    
    0 讨论(0)
提交回复
热议问题