0

I have the need to round a number for pricing sort of strangely as follows:

the value of an incoming price will be 3 decimal places (ie. 10.333)

It is necessary to round the first decimal place up if any number past said first decimal place is greater than 0.

for example:

10.300 = 10.3,
10.301 = 10.4,
10.333 = 10.4

before I go creating a custom method to do this I was wondering if anyone was aware of an existing usage/overload of Math.Round() or other already existing package to get this desired result?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Gazrok
  • 99
  • 2
  • 8
  • This Question might help you: [https://stackoverflow.com/questions/21599118/always-round-up-a-value-in-c-sharp](https://stackoverflow.com/questions/21599118/always-round-up-a-value-in-c-sharp). – Petr Nečas Jan 09 '23 at 14:36

3 Answers3

4

Math.Round has an overload that accepts a MidpointRounding enum value, which lets you specify the strategy for rounding.

In your case, you always want to round up, which is called ToPositiveInfinity.

Math.Round(yourValue, 1, System.MidpointRounding.ToPositiveInfinity)
gunr2171
  • 16,104
  • 25
  • 61
  • 88
0

Approach with Math.Ceiling()

decimal input = 10.300m;
decimal result = Math.Ceiling(input * 10m) / 10m;

https://dotnetfiddle.net/Vck4Oa

fubo
  • 44,811
  • 17
  • 103
  • 137
0
double d = 10.300;
var result= Math.Ceiling((decimal)d * 10) / 10;
Hossein Sabziani
  • 1
  • 2
  • 15
  • 20