-1

I have the value

8443.64625

and want to round it to 4 decimal places. When I use decimal.Round(8443.64625, 4, MidpointRounding.AwayFromZero)it gives the value

8443.6463

. So it seems to be round up because of the 5. What can I do to make it return the value

8443.6462

. I could convert it to string and then truncate after 4dp but I feel there has to be a more efficient way?

Bad Dub
  • 1,503
  • 2
  • 22
  • 52

4 Answers4

0

You Can Use this it will work fine Just Try it once. It will give You the result that you want. that is 8443.6462.

    Math.Round(8443.64625, 4)
  • 2
    That actually rounds to the nearest EVEN number - try `Math.Round(8445.64635, 4)` - it will return `8445.6464` (which isn't what the OP wants, they want that to return `8445.6463`). – Matthew Watson Mar 02 '20 at 13:52
  • @MatthewWatson I want to return 8443.6462 which this seems to do – Bad Dub Mar 02 '20 at 13:59
  • @BadDub But what do you want `8445.64635` to return? (This is not the same number as `8445.64625` - look at it carefully! One ends with `35` and the other with `25`.) – Matthew Watson Mar 02 '20 at 14:05
0

It was suggested to use decimal.Round(8443.64625, 4, MidpointRounding.ToEven) by someone but that comment seems to have been removed.

MidpointRounding.ToEven works for the scenario I posted yes, but if the value was 8443.64629 it would produce 8443.6463. I need it to truncate without rounding.

I came across this answer which seems to truncate after 4dp with no rounding.

public static decimal TruncateValue(this decimal num, int significantDigits)
{
    decimal y = (decimal)Math.Pow(10, significantDigits);
    return Math.Truncate(num * y) / y;
}
Bad Dub
  • 1,503
  • 2
  • 22
  • 52
0

This works

var num = 8443.64625;

var roundedNum = Math.Round(num, 4, MidpointRounding.ToEven);
ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • It works for the scenario I posted yes, but if the value was 8443.64629 it would produce 8443.6463. I need it to truncate without rounding. – Bad Dub Mar 02 '20 at 14:14
0

I don't know if this has been answered yet but, you could use Truncate.

It's not 'rounding' per se but you would get the result I believe you want.

ie:

double num = 8443.64625;
Math.Truncate(10000 * num) / 10000

returns

8443.6462
JamesS
  • 2,167
  • 1
  • 11
  • 29