Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
<pre lang="PHP">echo 128.23 - (118.23 + 10);

Python
print(128.23 - (118.23 + 10))

JavaScript
console.log(128.23 - (118.23 + 10))


I tried in PHP, JavaScript and Python

All those calcs does not return 0 or 0.00, but return -2.842170943040401e-14

Somebody can explain to me why this happen?

What I have tried:

Actually i do not even know for where begin to understand because this have no sense to me
Posted
Updated 6-Feb-23 2:59am
Comments
CHill60 6-Feb-23 7:35am    
This PDF from someone's degree course might help to explain https://people.cs.vt.edu/~asandu/Courses/CS3414/comp_arithm.pdf[^]
[no name] 6-Feb-23 13:28pm    
You also have to appreciate what a "tiny" number e-14 is. With floating point, you generally ROUND to 0, or 1-4 decimals for presentation which gets rid of the problem. In other situations, accept negative numbers (as zero) if you find these small difference and which you can account for.

 
Share this answer
 
Comments
OriginalGriff 6-Feb-23 9:01am    
:thumbsup:
To add to what Richard has - rightly - said ...

Try it in C# using different numeric types: Double, Float, and Decimal:
C#
Console.WriteLine(128.23 - (118.23 + 10));
Console.WriteLine(128.23f - (118.23f + 10f));
Console.WriteLine(128.23m - (118.23m + 10m));
The results probably aren't what you expected:
-2.8421709430404E-14
-1.525879E-05
0.00
That's why .NET has a Decimal numeric type.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900