简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM