5 ms·
Using floats to represent currency is a big no-no. Floats have limited precision, and some numbers aren't representable by floats. Go try adding 0.1 to itself o
by reikonomusha 13y ago
Using floats to represent currency is a big no-no. Floats have limited precision, and some numbers aren't representable by floats. Go try adding 0.1 to itself over and over again in your favorite implementation.
It is better to represent as integers or fixed-precision numbers. That way, you are dealing with exact quantities.
- negamax 13y agoTo me it seems like floats are being converted to int and then code is working with it. I don't think this will create an issue unless the int is overflowing. Any failing testcase?
- SixSigma 13y ago> some numbers aren't representable by floats an infinite number of them in fact
- deleted 13y ago[deleted]
- SixSigma 13y agoTuring proved there's an uncountable set of numbers that cannot even be computed let alone represented
- skj 13y agoCould make all the same arguments against integers: - Limited precision, - Some numbers aren't representable, - Go try adding 1 to itself over and over again. That said, yes, floats are a bad idea for financial arithmetic.
- thaumasiotes 13y agoYou can make the same arguments against integers, but you'd need to be willfully blind to the context of the discussion. There are no monetary quantities that can't be represented as integers. Using a scheme that can't represent 1/3 to record numbers for which 1/3 is an illegal value doesn't present any practical or theoretical problems.
- skj 13y agoMy point was that the arguments presented were not the reasons that using floats to handle finance was a bad idea. Since, as I showed, they also applied to integers.
- ufo 13y agoSheesh, stop being so pedantic. Unlike computers, humans can infer extra meaning from the context around a sentence.
- andruby 13y agoAs an example in Ruby (2.1.1): x = 0.1 #=> 0.1 10.times { x+=0.1 } #=> 10 x #=> 1.0999999999999999
- klibertp 13y agoWorks in Racket (and should in other Schemes): -> (for/sum ([_ (in-range 10)]) (/ 1 10)) 1 Yeah, I know, I'm cheating - `(/ 1 10)` returns a rational? which is not flonum?. Using `0.1` makes it inexact like it should be: -> (for/sum ([_ (in-range 10)]) 0.1) 0.9999999999999999
- rodgerd 13y agoIt's even better to represent as binary coded decimal, Ulrich Drepper's opinions notwithstanding.
- orthecreedence 13y agoThat's why I like lisp: (/ 10 17) => 10/17 (+ (/ 10 17) (/ 4 9)) => 158/153 =]