3

I'm trying to round up a value using this formula Math.Ceiling(val * 20) / 20

T1 and T2 both showing equivalent result of 10.1, but will round up differently.

var a1 = 9.06;
var a2 = 1.04;
var b1 = 9.04;
var b2 = 1.06;

var t1 = a1 + a2;
var t2 = b1 + b2;

Console.WriteLine("T1: " + t1);
Console.WriteLine("T2: " + t2);
Console.WriteLine("Rounding T1: " + Math.Ceiling(t1 * 20) / 20);
Console.WriteLine("Rounding T2: " + Math.Ceiling(t2 * 20) / 20);

Result

T1: 10.1
T2: 10.1
Rounding T1: 10.15
Rounding T2: 10.1

Why T1 getting extra 0.05 ?

  • 2
    [Is floating point math broken?](https://stackoverflow.com/q/588004/7444103). – Jimi Jul 10 '19 at 04:07
  • To add to @Jimi's comment, https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html and https://www.floating-point-gui.de/ – Flydog57 Jul 10 '19 at 04:23

2 Answers2

5

Floating point numbers aren't exact. If you subtract 10.1 from both you get:

  1.77635683940025E-15
  0

And Ceiling amplifies this.

Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
5

This could be due to the precision of doubles. Not all doubles can be stored exactly, so some get modified a little to the nearest storable value.

Sohaib Jundi
  • 1,576
  • 2
  • 7
  • 15