Apr-16-2024, 01:45 PM
I don't know what PHP does to prevent the visible inaccuracy.
In modern programming languages, you don't see the real floating point value inclusive PHP.
An algorithm is used, to show the user a nicer representation of the floating point value.
But this does not always work (e.G. 0.2 + 0.1).
Ancient programming languages haven't used it, so the user was able to see the imprecision caused
by the conversion from 10base to binary.
The key point is, that you can't represent all decimal numbers as binary numbers.
But there are different solutions.
In modern programming languages, you don't see the real floating point value inclusive PHP.
An algorithm is used, to show the user a nicer representation of the floating point value.
But this does not always work (e.G. 0.2 + 0.1).
Ancient programming languages haven't used it, so the user was able to see the imprecision caused
by the conversion from 10base to binary.
The key point is, that you can't represent all decimal numbers as binary numbers.
But there are different solutions.
# slow, but precise from decimal import Decimal # the quotes are mandatory # if you use float literals, it's already imprecise before Decimal is instantiated a = Decimal("27.56") b = Decimal("13.78") print("Decimal:", a + b)
# Scientific rounding a = 27.56 b = 13.78 print("Round 2 decimal places:", round(a + b, 2))
# floor # ceil from math import ceil, floor a = 27.56 b = 13.78 print("floor:", floor(a+b)) print("ceil:", ceil(a+b))
# adding the two int => int # then divide by 100 => float a = 2756 b = 1378 print("Int addition", (a+b) / 100)
# not rounding, just formatting the output instead of changing the float itself a = 27.56 b = 13.78 c = a + b print(f"Output formatting: {c:.2f}")
Output:Decimal: 41.34
Round 2 decimal places: 41.34
floor: 41
ceil: 42
Int addition 41.34
Output formatting: 41.34
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!