3 ms·
Won't decimal floats still result in errors like this if the absolute value gets too large? You can avoid that by ensuring that the mantissa has enough digits t
by mikeash 10y ago
Won't decimal floats still result in errors like this if the absolute value gets too large? You can avoid that by ensuring that the mantissa has enough digits to hold the largest value you'll ever encounter with enough significance to represent the smallest value you'll ever encounter, but at that point you might as well use an integer with that smallest value as the unit.
- danbruc 10y agoOf course, you can push any system to its limits and you can certainly replace your calculations with integer arithmetics. But why would you? Decimal floating point types are readily available and usually offer enough range and precision for all practical purposes. So why reinvent the wheel? And just imagine the pain you are going to go through if you have to adjust your base denomination, say because the law suddenly requires two additional digits of precision. You will have to touch every number you ever stored somewhere. Someone else in the comments mentioned arbitrary precision arithmetics, but even those don't solve all your problems magically. Not only are they comparatively slow and more cumbersome to deal with due to their variable length nature, but they still fail to correctly deal with one third, so rounding will still be required unless you manage to avoid all the bad numbers. You may then be tempted to switch to a rational number type with arbitrary precision integers as numerator and denominator. But while you now solved the problem with the one third, you still have to approximate irrational numbers and transcendental functions, for example Euler's constant, which is not unlikely to appear in interest calculations. So you still have to think about rounding, even if possibly in less places.
- mhluongo 10y agoUse fixed-point decimal math.