Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Math.Round issue with x.95

Tags:

c#

Just came across one strange issue:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08

But...

Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.1

Why is this happening? I'd like my result to be 113.09! Is that possible?

Thx

like image 929
David Tabatadze Avatar asked Dec 20 '22 01:12

David Tabatadze


1 Answers

Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.1

That is even. Read it with two decimal places:

113.10

10 would be the even part. The trimmed right zero is just making it look odd ("odd" in the sense of "not even", not to be confused as "odd" meaning "weird"), but that would be why it is showing that way.

Also, your examples in your question are inaccurate. Here is the output from those, which would further fortify why you're getting x.1 as your output:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08

Notice that rounding 113.075 ToEven results in 113.08, not 113.07.

Full example:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.1

Which can also be read as:

Math.Round(113.065, 2, MidpointRounding.ToEven) => 113.06
Math.Round(113.075, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.085, 2, MidpointRounding.ToEven) => 113.08
Math.Round(113.095, 2, MidpointRounding.ToEven) => 113.10

If the output in your question is really what you're looking to get... (i.e. if that really is your desired output, and you just want to know what you have to do to get that output)

Math.Floor(113.065 * 100) / 100 => 113.06
Math.Floor(113.075 * 100) / 100 => 113.07
Math.Floor(113.085 * 100) / 100 => 113.08
Math.Floor(113.095 * 100) / 100 => 113.09
like image 93
Thomas Stringer Avatar answered Jan 02 '23 02:01

Thomas Stringer