Round to 25, 50, 75, 100

后端 未结 5 2005
说谎
说谎 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.

提交回复
热议问题