Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same value rounding up giving different answer [duplicate]

Tags:

c#

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 ?

like image 592
Mohd Fuad Yazid Avatar asked Nov 29 '25 18:11

Mohd Fuad Yazid


2 Answers

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

  1.77635683940025E-15
  0

And Ceiling amplifies this.

like image 120
Ian Mercer Avatar answered Dec 01 '25 08:12

Ian Mercer


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.

like image 29
Sohaib Jundi Avatar answered Dec 01 '25 09:12

Sohaib Jundi