Mattlinux1
Mattlinux1

Reputation: 807

C# and PHP show two different results for a calculation with the same code logic

I have two sets of code one in PHP that i'm trying to get to work and one in C# both show slightly different values.

Below is the C# example:

decimal dayrate = l.dRate * balance / 36500;
Console.WriteLine("dayrate: {0}", dayrate); //dayrate output = 0.0582191780821917808219178082

The PHP example:

$dayrate = $row['dRate'] * $balance / 36500; 
echo "Dayrate: $dayrate"; //dayrate output = 0.058219178082192

Why is this and can it be corrected in the PHP example.

Upvotes: 1

Views: 267

Answers (2)

Benjamin
Benjamin

Reputation: 900

You're running into precision problems.

  • The C# decimal class is a 128-bit decimal value accurate to around 28 decimal places.
  • PHPs FLOAT class is a 64-bit decimal value accurate to around 15 decimal places.

You can fix this by using arbitrarily sized decimals in PHP:

BC Math

Or by using the double class in C#, which matches the PHP Float class.

If you need the values to match exactly, there isn't a whole lot you can do if you're problem uses irrational numbers. You should look at your programs requirement and decide on what precision is required, then round or truncate values to that precision.

Upvotes: 3

Renzo Robles
Renzo Robles

Reputation: 714

It is basicaly for datatype. In C# use decimal for long numbers, that for the result is most exactly. In php you must use Float Datatype for it.

Upvotes: 1

Related Questions